// 内联敏感词检测模块（避免动态加载问题）
class SensitiveWordDetector {
  constructor() {
    this.sensitiveWords = [];
  }

  setSensitiveWords(wordsString) {
    if (!wordsString || typeof wordsString !== "string") {
      this.sensitiveWords = [];
      return;
    }

    // 支持中英文逗号分隔
    this.sensitiveWords = wordsString
      .split(/[,，]/)
      .map((word) => word.trim())
      .filter((word) => word.length > 0);
  }

  detectSensitiveWords(text) {
    if (!text || typeof text !== "string") {
      return { hasSensitiveWord: false, matchedWords: [] };
    }

    if (this.sensitiveWords.length === 0) {
      return { hasSensitiveWord: false, matchedWords: [] };
    }

    const matchedWords = [];
    const textLower = text.toLowerCase();

    for (const word of this.sensitiveWords) {
      if (word && word.trim()) {
        const wordLower = word.trim().toLowerCase();

        // 使用更精确的匹配方式
        let isMatched = false;

        // 方式1: 完整词匹配（推荐）
        try {
          const regex = new RegExp(
            `\\b${wordLower.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`,
            "i"
          );
          isMatched = regex.test(text);
        } catch (regexError) {
          // 如果正则表达式失败，回退到简单包含检查
          isMatched = textLower.includes(wordLower);
        }

        // 方式2: 对于中文，使用直接包含检查（因为中文没有词边界）
        if (!isMatched && /[\u4e00-\u9fff]/.test(wordLower)) {
          isMatched = textLower.includes(wordLower);
        }

        if (isMatched) {
          matchedWords.push(word);
        }
      }
    }

    const hasSensitiveWord = matchedWords.length > 0;

    return { hasSensitiveWord, matchedWords };
  }

  /**
   * 检查循环元素是否应该跳过（简化版本）
   * @param {Element} element - 循环元素
   * @param {object} config - 敏感词检测配置
   * @returns {Promise<object>} - {shouldSkip: boolean, reason: string, matchedWords: string[]}
   */
  async checkShouldSkipElement(element, config) {
    try {
      // 如果未启用敏感词检测，不跳过
      if (!config.enabled) {
        return { shouldSkip: false, reason: "", matchedWords: [] };
      }

      // 如果没有配置敏感词，不跳过
      if (!config.sensitiveWords || config.sensitiveWords.trim() === "") {
        return { shouldSkip: false, reason: "", matchedWords: [] };
      }

      // 设置敏感词列表
      this.setSensitiveWords(config.sensitiveWords);

      // 提取文本内容
      let text = "";
      if (config.locatorValue && config.locatorValue.trim()) {
        // 如果指定了目标选择器，查找目标元素
        const targetElement = element.querySelector(config.locatorValue);
        if (targetElement) {
          text = targetElement.innerText || targetElement.textContent || "";
        } else {
          // 如果找不到目标元素，使用整个元素的文本
          text = element.innerText || element.textContent || "";
        }
      } else {
        // 如果没有指定目标选择器，使用整个元素的文本
        text = element.innerText || element.textContent || "";
      }

      console.log(
        "📝 提取的文本内容:",
        text.substring(0, 100) + (text.length > 100 ? "..." : "")
      );

      // 检测敏感词
      const detection = this.detectSensitiveWords(text);

      if (detection.hasSensitiveWord) {
        const reason = `包含敏感词: ${detection.matchedWords.join(", ")}`;
        console.log("🚫 跳过循环元素:", reason);
        return {
          shouldSkip: true,
          reason,
          matchedWords: detection.matchedWords,
        };
      }

      return { shouldSkip: false, reason: "", matchedWords: [] };
    } catch (error) {
      console.error("❌ 敏感词检测失败:", error);
      // 检测失败时不跳过，避免影响正常流程
      return { shouldSkip: false, reason: "检测失败", matchedWords: [] };
    }
  }
}

// 创建全局实例
if (!window.SensitiveWordDetector) {
  window.SensitiveWordDetector = SensitiveWordDetector;
}

// 智能超时控制器
class SmartTimeoutController {
  constructor(timeoutMs, stepName) {
    this.timeoutMs = timeoutMs;
    this.stepName = stepName;
    this.startTime = Date.now();
    this.pausedTime = 0;
    this.isPaused = false;
    this.pauseStartTime = null;
    this.timeoutId = null;
    this.rejectFn = null;
  }

  // 开始超时倒计时
  start() {
    if (this.timeoutId || !this.isPaused) return; // 已经启动或未暂停

    this.isPaused = false;
    const remainingTime = this.timeoutMs - this.pausedTime;

    this.timeoutId = setTimeout(() => {
      if (this.rejectFn && !this.isPaused) {
        this.rejectFn(new Error(`步骤执行超时: ${this.stepName}`));
      }
    }, remainingTime);
  }

  // 暂停超时倒计时
  pause() {
    if (this.isPaused) return; // 已经暂停

    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
      this.pauseStartTime = Date.now();
    }
    this.isPaused = true;
  }

  // 恢复超时倒计时
  resume() {
    if (!this.isPaused) return;

    this.pausedTime += Date.now() - this.pauseStartTime;
    this.isPaused = false;
    this.pauseStartTime = null;
    this.start();
  }

  // 清除超时
  clear() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    }
    this.isPaused = true;
    this.rejectFn = null; // 清除reject函数，防止超时触发
  }

  // 创建超时Promise
  createTimeoutPromise() {
    return new Promise((_, reject) => {
      this.rejectFn = reject;
      // 默认不启动超时，需要手动启动
      this.isPaused = true;
    });
  }
}

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log("Content script收到消息:", request);

  // 处理ping请求，用于检测content script是否已加载
  if (request.action === "ping") {
    console.log("收到ping请求");
    sendResponse({
      success: true,
      status: "ready",
      message: "Content script已加载",
    });
    return true;
  }

  // 处理重置引擎请求
  if (request.action === "resetEngine") {
    try {
      console.log("🔄 收到重置引擎请求");

      // 清除可能存在的引擎实例
      if (window.UniversalAutomationEngine) {
        // 移除旧的脚本标签
        const oldScripts = document.querySelectorAll(
          'script[data-automation-engine="true"]'
        );
        oldScripts.forEach((script) => {
          script.remove();
          console.log("🗑️ 已移除旧的引擎脚本");
        });

        // 清除全局引用
        delete window.UniversalAutomationEngine;
        console.log("✅ 自动化引擎全局引用已清除");
      }

      sendResponse({ success: true, message: "引擎已重置" });
    } catch (error) {
      console.error("❌ 重置引擎失败:", error);
      sendResponse({ success: false, error: error.message });
    }
    return true;
  }

  // 处理在当前窗口中执行单个操作的请求
  if (request.action === "executeOperation") {
    console.log("🎯 收到在当前窗口中执行操作请求:", request.operation);

    (async () => {
      try {
        const operation = request.operation;

        // 执行单个操作
        await executeSubOperation(operation, null);

        console.log("✅ 在当前窗口中执行操作成功");
        sendResponse({
          success: true,
          message: "操作执行成功"
        });
      } catch (error) {
        console.error("❌ 在当前窗口中执行操作失败:", error);
        sendResponse({
          success: false,
          error: error.message
        });
      }
    })();

    return true; // 保持消息通道开放
  }

  // 处理通用自动化工作流执行
  if (request.action === "executeWorkflow") {
    console.log(
      "🔧 [DEBUG] 收到工作流执行请求，工作流数据:",
      JSON.stringify(request.data, null, 2)
    );

    // 验证工作流数据结构
    if (request.data && request.data.steps) {
      request.data.steps.forEach((step, index) => {
        console.log(`🔧 [DEBUG] 步骤 ${index + 1}:`, {
          type: step.type,
          name: step.name,
          locator: step.locator,
          hasLocator: !!step.locator,
          locatorStrategy: step.locator?.strategy || step.locator?.type,
          locatorValue: step.locator?.value,
        });
      });
    }
    // 检查是否包含新窗口操作
    console.log("🔍 开始检查是否包含新窗口操作...");
    const hasNewWindowOperations = request.data.steps.some((step, index) => {
      let hasNewWindow = step.opensNewWindow ||
        step.type === 'closeWindow' ||
        step.action === 'closeWindow';

      // 检查容器循环内部的子操作
      if (step.type === 'loop' && step.subOperations && step.subOperations.length > 0) {
        const hasSubNewWindow = step.subOperations.some(subOp =>
          subOp.opensNewWindow ||
          subOp.type === 'closeWindow' ||
          subOp.action === 'closeWindow'
        );
        if (hasSubNewWindow) {
          hasNewWindow = true;
          console.log(`🔍 容器循环 ${step.name} 内部包含新窗口操作`);
        }
      }

      console.log(`🔍 步骤 ${index + 1} (${step.name}): opensNewWindow=${step.opensNewWindow}, type=${step.type}, action=${step.action}, hasNewWindow=${hasNewWindow}`);
      return hasNewWindow;
    });

    console.log(`🔍 新窗口操作检测结果: ${hasNewWindowOperations}`);

    if (hasNewWindowOperations) {
      console.log("🪟 检测到新窗口操作，转交background script处理");

      // 转发到background script处理
      console.log("🪟 [浮层面板-DEBUG] 正在发送executeWorkflow消息到background...");
      console.log("🪟 [浮层面板-DEBUG] 发送的数据:", JSON.stringify(request.data, null, 2));

      chrome.runtime.sendMessage({
        action: "executeWorkflow",
        data: request.data
      }).then((result) => {
        console.log("🪟 [浮层面板-DEBUG] 收到background响应:", result);
        console.log("🪟 [浮层面板-DEBUG] 响应类型:", typeof result);
        console.log("🪟 [浮层面板-DEBUG] 响应内容:", JSON.stringify(result, null, 2));
        console.log("✅ 新窗口工作流执行成功，发送状态更新到浮层");

        // 发送成功状态到浮层
        if (typeof sendStatusToFloatingPanel === 'function') {
          sendStatusToFloatingPanel({
            isRunning: false,
            isPaused: false,
            message: '执行完成'
          });
        } else {
          // 直接发送消息到浮层
          const message = {
            type: 'FROM_CONTENT_SCRIPT',
            action: 'executionStatusUpdate',
            data: {
              isRunning: false,
              isPaused: false,
              message: '执行完成'
            },
            timestamp: Date.now()
          };
          window.postMessage(message, '*');
          console.log('📤 直接发送状态更新到浮层:', message.data);
        }

        sendResponse({ success: true, result });
      }).catch((error) => {
        console.error("转发到background执行失败:", error);

        // 发送错误状态到浮层
        if (typeof sendStatusToFloatingPanel === 'function') {
          sendStatusToFloatingPanel({
            isRunning: false,
            isPaused: false,
            message: '执行失败: ' + error.message
          });
        } else {
          // 直接发送消息到浮层
          const message = {
            type: 'FROM_CONTENT_SCRIPT',
            action: 'executionStatusUpdate',
            data: {
              isRunning: false,
              isPaused: false,
              message: '执行失败: ' + error.message
            },
            timestamp: Date.now()
          };
          window.postMessage(message, '*');
          console.log('📤 直接发送错误状态到浮层:', message.data);
        }

        sendResponse({ success: false, error: error.message });
      });
    } else {
      executeUniversalWorkflow(request.data)
        .then((result) => {
          console.log("✅ 工作流执行成功，发送状态更新到浮层");

          // 发送成功状态到浮层
          if (typeof sendStatusToFloatingPanel === 'function') {
            sendStatusToFloatingPanel({
              isRunning: false,
              isPaused: false,
              message: '执行完成'
            });
          } else {
            // 直接发送消息到浮层
            const message = {
              type: 'FROM_CONTENT_SCRIPT',
              action: 'executionStatusUpdate',
              data: {
                isRunning: false,
                isPaused: false,
                message: '执行完成'
              },
              timestamp: Date.now()
            };
            window.postMessage(message, '*');
            console.log('📤 直接发送状态更新到浮层:', message.data);
          }

          sendResponse({ success: true, result });
        })
        .catch((error) => {
          console.error("执行通用工作流失败:", error);

          // 发送失败状态到浮层
          if (typeof sendStatusToFloatingPanel === 'function') {
            sendStatusToFloatingPanel({
              isRunning: false,
              isPaused: false,
              message: '执行失败: ' + error.message
            });
          } else {
            // 直接发送消息到浮层
            const message = {
              type: 'FROM_CONTENT_SCRIPT',
              action: 'executionStatusUpdate',
              data: {
                isRunning: false,
                isPaused: false,
                message: '执行失败: ' + error.message
              },
              timestamp: Date.now()
            };
            window.postMessage(message, '*');
            console.log('📤 直接发送错误状态到浮层:', message.data);
          }

          sendResponse({ success: false, error: error.message });
        });
    }

    return true;
  }

  // 处理来自插件的localStorage更新请求
  if (request.type === 'sendToLocalStorage') {
    const { key, value } = request.data;

    console.log(`📥 Content Script收到localStorage更新请求:`, {
      key: key,
      valueLength: value ? value.length : 0,
      currentValue: localStorage.getItem(key) ? localStorage.getItem(key).length : 0
    });

    localStorage.setItem(key, value);
    console.log(`✅ 已更新localStorage: ${key}`);

    // 通知浮层控制面板数据已更新
    if (key === 'automationWorkflows') {
      const message = {
        type: 'WORKFLOW_DATA_UPDATED',
        timestamp: Date.now()
      };
      window.postMessage(message, '*');
      console.log('📡 已通知浮层控制面板数据更新');

      // 验证数据是否正确保存
      const savedData = localStorage.getItem(key);
      if (savedData) {
        try {
          const workflows = JSON.parse(savedData);
          console.log(`✅ 验证：localStorage中现有 ${workflows.length} 个工作流`);
        } catch (error) {
          console.error('❌ 验证localStorage数据失败:', error);
        }
      }
    }

    sendResponse({ success: true });
    return true;
  }

  // 处理来自background script的数据同步请求
  if (request.action === 'syncToWebpageStorage') {
    const { key, value } = request.data;

    console.log(`📡 [数据同步-DEBUG] Content Script收到数据同步请求:`, {
      key: key,
      valueLength: value ? value.length : 0,
      currentValue: localStorage.getItem(key) ? localStorage.getItem(key).length : 0,
      url: window.location.href
    });

    // 更新localStorage
    localStorage.setItem(key, value);
    console.log(`✅ [数据同步-DEBUG] 已更新localStorage: ${key}`);

    // 通知浮层控制面板数据已更新
    if (key === 'automationWorkflows') {
      const message = {
        type: 'WORKFLOW_DATA_UPDATED',
        timestamp: Date.now()
      };
      window.postMessage(message, '*');
      console.log('📡 [数据同步-DEBUG] 已通知浮层控制面板数据更新');

      // 验证数据是否正确保存
      const savedData = localStorage.getItem(key);
      if (savedData) {
        try {
          const workflows = JSON.parse(savedData);
          console.log(`✅ [数据同步-DEBUG] 验证：localStorage中现有 ${workflows.workflows ? workflows.workflows.length : 0} 个工作流`);
        } catch (error) {
          console.error('❌ [数据同步-DEBUG] 验证localStorage数据失败:', error);
        }
      }
    }

    sendResponse({ success: true });
    return true;
  }

  // 处理来自background script的执行状态更新
  if (request.action === 'executionStatusUpdate') {
    console.log(`📡 [浮层面板-DEBUG] Content Script收到执行状态更新:`, request.data);

    // 🔧 [修复] 更新本地执行控制状态
    if (window.simplifiedExecutionControl) {
      // 更新运行状态
      if (request.data.hasOwnProperty('isRunning')) {
        window.simplifiedExecutionControl.isRunning = request.data.isRunning;
        console.log(`🔧 [修复] 更新本地isRunning状态为:`, request.data.isRunning);

        // 🔧 [修复] 同步更新全局停止标志
        if (!request.data.isRunning) {
          window.globalExecutionStopped = true;
          console.log(`🔧 [修复] 设置全局停止标志为: true`);
        }
      }

      // 更新暂停状态
      if (request.data.hasOwnProperty('isPaused')) {
        const wasAlreadyPaused = window.simplifiedExecutionControl.isPaused;
        window.simplifiedExecutionControl.isPaused = request.data.isPaused;
        console.log(`🔧 [修复] 更新本地isPaused状态为:`, request.data.isPaused);

        // 如果从暂停状态恢复，解决暂停Promise
        if (wasAlreadyPaused && !request.data.isPaused && window.simplifiedExecutionControl.pauseResolve) {
          console.log(`🔧 [修复] 解决暂停Promise，恢复执行`);
          window.simplifiedExecutionControl.pauseResolve();
          window.simplifiedExecutionControl.pauseResolve = null;
          window.simplifiedExecutionControl.pausePromise = null;
        }
      }
    } else {
      // 🔧 [修复] 如果执行控制对象不存在，直接更新全局标志
      if (request.data.hasOwnProperty('isRunning') && !request.data.isRunning) {
        window.globalExecutionStopped = true;
        console.log(`🔧 [修复] 执行控制对象不存在，设置全局停止标志为: true`);
      }
    }

    // 转发状态更新到浮层控制面板
    const message = {
      type: 'FROM_CONTENT_SCRIPT',
      action: 'executionStatusUpdate',
      data: request.data,
      timestamp: Date.now()
    };

    window.postMessage(message, '*');
    console.log(`📡 [浮层面板-DEBUG] 已转发状态更新到浮层控制面板:`, request.data.message);

    sendResponse({ success: true });
    return true;
  }

  if (request.action === "performAction") {
    performAction(request.config)
      .then((result) => {
        sendResponse({ success: true, ...result });
      })
      .catch((error) => {
        console.error("执行操作失败:", error);
        sendResponse({ success: false, error: error.message });
      });

    // 返回true表示我们将异步发送响应
    return true;
  }

  if (request.action === "testElementLocator") {
    testElementLocator(request.locator)
      .then((result) => {
        sendResponse({ success: true, ...result });
      })
      .catch((error) => {
        console.error("测试元素定位失败:", error);
        sendResponse({ success: false, error: error.message });
      });

    return true;
  }

  // 处理定位器测试请求
  if (request.action === "testLocator") {
    try {
      const result = testLocatorElements(request.locator);
      sendResponse({ success: true, count: result.count });
    } catch (error) {
      console.error("测试定位器失败:", error);
      sendResponse({ success: false, error: error.message });
    }
    return true;
  }

  // 处理条件测试请求
  if (request.action === "testCondition") {
    try {
      const result = testCondition(request.condition);
      sendResponse(result);
    } catch (error) {
      console.error("测试条件失败:", error);
      sendResponse({ success: false, error: error.message });
    }
    return true;
  }

  // 处理属性条件测试请求
  if (request.action === "testAttributeCondition") {
    try {
      testAttributeCondition(request.data)
        .then((result) => {
          sendResponse(result);
        })
        .catch((error) => {
          console.error("测试属性条件失败:", error);
          sendResponse({ success: false, error: error.message });
        });
    } catch (error) {
      console.error("测试属性条件失败:", error);
      sendResponse({ success: false, error: error.message });
    }
    return true;
  }

  // 处理清除测试高亮请求
  if (request.action === "clearTestHighlights") {
    try {
      clearTestHighlights();
      sendResponse({ success: true });
    } catch (error) {
      console.error("清除测试高亮失败:", error);
      sendResponse({ success: false, error: error.message });
    }
    return true;
  }

  // 处理暂停执行请求 - 转发到background script
  if (request.action === "pauseExecution") {
    console.log("🔧 [浮层面板-DEBUG] Content script收到暂停请求，转发到background script");

    // 直接转发到background script，不在content script中处理
    chrome.runtime.sendMessage({
      action: "pauseExecution"
    }).then(response => {
      console.log("✅ [浮层面板-DEBUG] 暂停请求已转发到background script:", response);
      sendResponse({ success: true, response: response });
    }).catch(error => {
      console.error("❌ [浮层面板-DEBUG] 转发暂停请求失败:", error);
      sendResponse({ success: false, error: error.message });
    });

    return true;
  }

  // 处理继续执行请求 - 转发到background script
  if (request.action === "resumeExecution") {
    console.log("🔧 [浮层面板-DEBUG] Content script收到恢复请求，转发到background script");

    // 直接转发到background script，不在content script中处理
    chrome.runtime.sendMessage({
      action: "resumeExecution"
    }).then(response => {
      console.log("✅ [浮层面板-DEBUG] 恢复请求已转发到background script:", response);
      sendResponse({ success: true, response: response });
    }).catch(error => {
      console.error("❌ [浮层面板-DEBUG] 转发恢复请求失败:", error);
      sendResponse({ success: false, error: error.message });
    });

    return true;
  }

  // 处理获取执行状态请求
  if (request.action === "getExecutionStatus") {
    try {
      let executionStatus = {
        isRunning: false,
        isPaused: false,
        currentStep: 0,
        totalSteps: 0,
        completedSteps: 0,
        startTime: null,
        currentOperation: null,
      };

      if (window.simplifiedExecutionControl) {
        executionStatus = {
          isRunning: window.simplifiedExecutionControl.isRunning,
          isPaused: window.simplifiedExecutionControl.isPaused,
          currentStep: window.simplifiedExecutionControl.currentStep || 0,
          totalSteps: window.simplifiedExecutionControl.totalSteps || 0,
          completedSteps: window.simplifiedExecutionControl.completedSteps || 0,
          startTime: window.simplifiedExecutionControl.startTime,
          currentOperation: window.simplifiedExecutionControl.currentOperation,
        };
      }

      console.log("🔧 [DEBUG] 返回执行状态:", executionStatus);
      sendResponse({ success: true, ...executionStatus });
    } catch (error) {
      console.error("获取执行状态失败:", error);
      sendResponse({ success: false, error: error.message });
    }
    return true;
  }

  // 处理停止执行请求 - 转发到background script
  if (request.action === "stopExecution") {
    console.log("🔧 [浮层面板-DEBUG] Content script收到停止请求，转发到background script");

    // 直接转发到background script，不在content script中处理
    chrome.runtime.sendMessage({
      action: "stopExecution"
    }).then(response => {
      console.log("✅ [浮层面板-DEBUG] 停止请求已转发到background script:", response);
      sendResponse({ success: true, response: response });
    }).catch(error => {
      console.error("❌ [浮层面板-DEBUG] 转发停止请求失败:", error);
      sendResponse({ success: false, error: error.message });
    });

    return true;
  }

  if (request.action === "findAllElements") {
    findAllElements(request.locator)
      .then((result) => {
        sendResponse({ success: true, ...result });
      })
      .catch((error) => {
        console.error("查找所有元素失败:", error);
        sendResponse({ success: false, error: error.message });
      });

    return true;
  }

  if (request.action === "performActionOnElementByIndex") {
    performActionOnElementByIndex(
      request.locator,
      request.index,
      request.actionType,
      request.inputText
    )
      .then((result) => {
        sendResponse({ success: true, ...result });
      })
      .catch((error) => {
        console.error("按索引操作元素失败:", error);
        sendResponse({ success: false, error: error.message });
      });

    return true;
  }
});

/**
 * 测试元素定位并高亮显示
 * @param {object} locator - 元素定位配置
 * @returns {Promise<object>} - 执行结果
 */
async function testElementLocator(locator) {
  try {
    console.log(`测试定位元素:`, locator);

    // 查找元素
    const elements = await findElementsByStrategy(
      locator.strategy,
      locator.value
    );

    if (elements.length === 0) {
      throw new Error("未找到匹配元素");
    }

    // 移除之前的高亮
    removeHighlights();

    // 高亮显示找到的元素
    elements.forEach((element) => {
      highlightElement(element);
    });

    // 5秒后移除高亮
    setTimeout(removeHighlights, 5000);

    return {
      count: elements.length,
      message: `找到 ${elements.length} 个匹配元素并已高亮显示`,
    };
  } catch (error) {
    console.error("测试元素定位时出错:", error);
    throw error;
  }
}

/**
 * 高亮显示元素
 * @param {HTMLElement} element - 要高亮的元素
 */
function highlightElement(element) {
  // 保存原始样式
  const originalOutline = element.style.outline;
  const originalOutlineOffset = element.style.outlineOffset;
  const originalPosition = element.style.position;
  const originalZIndex = element.style.zIndex;

  // 设置高亮样式
  element.style.outline = "2px solid red";
  element.style.outlineOffset = "2px";

  // 确保元素在前面
  if (getComputedStyle(element).position === "static") {
    element.style.position = "relative";
  }
  element.style.zIndex = "10000";

  // 保存元素引用以便之后恢复
  element.setAttribute(
    "data-highlight-original",
    JSON.stringify({
      outline: originalOutline,
      outlineOffset: originalOutlineOffset,
      position: originalPosition,
      zIndex: originalZIndex,
    })
  );
}

/**
 * 移除所有高亮
 */
function removeHighlights() {
  const highlightedElements = document.querySelectorAll(
    "[data-highlight-original]"
  );

  highlightedElements.forEach((element) => {
    try {
      const original = JSON.parse(
        element.getAttribute("data-highlight-original")
      );

      // 恢复原始样式
      element.style.outline = original.outline;
      element.style.outlineOffset = original.outlineOffset;
      element.style.position = original.position;
      element.style.zIndex = original.zIndex;

      // 移除属性
      element.removeAttribute("data-highlight-original");
    } catch (error) {
      console.error("恢复元素样式时出错:", error);
    }
  });
}

/**
 * 查找所有匹配的元素
 * @param {object} locator - 元素定位配置
 * @returns {Promise<object>} - 执行结果，包含元素数量
 */
async function findAllElements(locator) {
  try {
    const elements = await findElementsByStrategy(
      locator.strategy,
      locator.value
    );

    // 返回元素数量和简要描述
    return {
      count: elements.length,
      message: `找到 ${elements.length} 个匹配元素`,
      elements: elements.map(elementToString),
    };
  } catch (error) {
    console.error("查找所有元素时出错:", error);
    throw error;
  }
}

/**
 * 根据索引对元素执行操作
 * @param {object} locator - 元素定位配置
 * @param {number} index - 元素索引
 * @param {string} actionType - 操作类型
 * @param {string} inputText - 输入文本（如果是输入操作）
 * @returns {Promise<object>} - 执行结果
 */
async function performActionOnElementByIndex(
  locator,
  index,
  actionType,
  inputText
) {
  try {
    console.log(`按索引 ${index} 操作元素:`, locator);

    const elements = await findElementsByStrategy(
      locator.strategy,
      locator.value
    );

    if (elements.length === 0) {
      throw new Error("未找到匹配元素");
    }

    if (index < 0 || index >= elements.length) {
      throw new Error(`索引 ${index} 超出范围 (0-${elements.length - 1})`);
    }

    const element = elements[index];
    console.log(`获取到索引 ${index} 的元素:`, elementToString(element));

    // 根据操作类型执行相应动作
    switch (actionType) {
      case "click":
        await clickElement(element);
        break;

      case "input":
        if (inputText === undefined) {
          throw new Error("输入操作需要提供输入文本");
        }
        await inputText(element, inputText);
        break;

      default:
        throw new Error(`不支持的操作类型: ${actionType}`);
    }

    return {
      message: `成功对索引 ${index} 的元素执行${actionType}操作`,
      element: elementToString(element),
    };
  } catch (error) {
    console.error("按索引操作元素时出错:", error);
    throw error;
  }
}

/**
 * 执行指定的页面操作
 * @param {object} config - 操作配置
 * @returns {Promise<object>} - 执行结果
 */
async function performAction(config) {
  try {
    // 兼容性处理：支持 config.action 和 config.type 字段
    const actionType = config.action || config.type;

    if (!actionType) {
      throw new Error(`操作类型未定义: ${JSON.stringify(config)}`);
    }

    // 等待操作不需要查找元素
    if (actionType === "wait") {
      const waitTime = config.waitTime || config.duration || 3000; // 默认3秒
      console.log(`执行等待操作: ${waitTime}毫秒`);

      // 返回一个Promise，在指定的时间后解析
      await new Promise((resolve) => setTimeout(resolve, waitTime));

      return {
        message: `成功等待 ${waitTime} 毫秒`,
      };
    }

    // 智能等待操作
    if (actionType === "smartWait") {
      const timeout = config.timeout || 30000;
      const checkInterval = config.checkInterval || 500;

      console.log(`执行智能等待操作，等待元素: ${config.locator?.value}`);

      if (!config.locator) {
        throw new Error("智能等待操作需要定位器配置");
      }

      // 等待元素出现
      const startTime = Date.now();
      while (Date.now() - startTime < timeout) {
        try {
          const element = await findElementByStrategy(
            config.locator.strategy,
            config.locator.value
          );
          if (element) {
            return {
              message: `智能等待成功，元素已出现: ${config.locator.value}`,
              element: elementToString(element),
            };
          }
        } catch (error) {
          // 元素未找到，继续等待
        }
        await new Promise((resolve) => setTimeout(resolve, checkInterval));
      }

      throw new Error(`智能等待超时: ${config.locator.value}`);
    }

    // 关闭窗口操作
    if (actionType === "closeWindow") {
      console.log(`执行关闭窗口操作: ${config.closeTarget}`);

      // 通知background脚本处理关闭窗口
      if (typeof chrome !== 'undefined' && chrome.runtime) {
        try {
          const response = await chrome.runtime.sendMessage({
            action: 'handleCloseWindow',
            config: config
          });

          if (response && response.success) {
            return {
              message: `窗口关闭成功: ${response.message}`,
            };
          } else {
            throw new Error(response?.error || "关闭窗口失败");
          }
        } catch (error) {
          throw new Error(`关闭窗口失败: ${error.message}`);
        }
      } else {
        // 如果没有chrome API，尝试关闭当前窗口
        if (config.closeTarget === "current") {
          window.close();
          return {
            message: "窗口关闭命令已发送",
          };
        } else {
          throw new Error("无chrome API支持，无法关闭指定窗口");
        }
      }
    }

    // 对于其他操作，需要查找元素
    // 根据定位策略查找元素
    const element = await findElementByStrategy(
      config.locator.strategy,
      config.locator.value
    );

    // 根据操作类型执行相应动作
    switch (actionType) {
      case "click":
        await clickElement(element);
        break;

      case "input":
        await inputText(element, config.inputText || config.text);
        break;

      default:
        throw new Error(`不支持的操作类型: ${actionType}`);
    }

    return {
      message: "操作成功执行",
      element: elementToString(element),
    };
  } catch (error) {
    throw error;
  }
}

/**
 * 将元素转换为字符串表示，用于日志输出
 */
function elementToString(element) {
  if (!element) return "null";

  let str = element.tagName.toLowerCase();
  if (element.id) str += `#${element.id}`;

  // 安全地获取className，处理SVG元素的特殊情况
  try {
    let className = "";
    if (element.className) {
      // 对于SVG元素，className是SVGAnimatedString对象
      if (typeof element.className === "string") {
        className = element.className;
      } else if (element.className.baseVal !== undefined) {
        className = element.className.baseVal;
      } else if (element.className.animVal !== undefined) {
        className = element.className.animVal;
      }
    }
    if (className) {
      str += `.${className.replace(/\s+/g, ".")}`;
    }
  } catch (error) {
    // 如果获取className失败，忽略错误继续
    console.debug("获取元素className失败:", error);
  }

  return str;
}

/**
 * 根据定位策略查找元素
 * @param {string} strategy - 定位策略
 * @param {string} value - 定位值
 * @returns {Promise<HTMLElement>} - 找到的元素
 */
async function findElementByStrategy(strategy, value, timeout = 5000) {
  console.log(`尝试使用${strategy}策略查找元素: ${value}`);

  switch (strategy) {
    case "id":
      return await findElement("id", value, timeout);

    case "css":
      return await findElement("css", value, timeout);

    case "xpath":
      return await findElementByXPath(value, timeout);

    case "text":
      return await findElementByText(value, ["*"], timeout);

    case "contains":
      return await findElementContainingText(value, ["*"], timeout);

    default:
      throw new Error(`不支持的定位策略: ${strategy}`);
  }
}

/**
 * 根据定位策略查找所有匹配元素
 * @param {string} strategy - 定位策略
 * @param {string} value - 定位值
 * @returns {Promise<HTMLElement[]>} - 找到的所有元素数组
 */
async function findElementsByStrategy(strategy, value, timeout = 5000) {
  console.log(`尝试使用${strategy}策略查找所有匹配元素: ${value}`);

  // 对于基本选择器，尝试立即查找而不使用轮询
  if (["id", "css", "xpath"].includes(strategy)) {
    try {
      // 对于基本的DOM选择器，直接尝试一次查询
      let elements = await performSingleElementSearch(strategy, value);

      // 如果找到了元素，立即返回结果
      if (elements.length > 0) {
        console.log(
          `使用${strategy}策略立即找到 ${elements.length} 个匹配元素`
        );
        return elements;
      }
    } catch (error) {
      console.warn(`立即查找元素失败:`, error);
      // 继续使用轮询方式作为备选方案
    }
  }

  // 使用异步轮询避免阻塞主线程
  return await performAsyncElementSearch(strategy, value, timeout);
}

/**
 * 异步元素搜索，避免阻塞主线程
 * @param {string} strategy - 定位策略
 * @param {string} value - 定位值
 * @param {number} timeout - 超时时间
 * @returns {Promise<HTMLElement[]>} - 找到的元素数组
 */
async function performAsyncElementSearch(strategy, value, timeout) {
  const startTime = Date.now();
  let elements = [];

  // 减少轮询频率，特别是对于文本查找
  const pollingInterval =
    strategy === "text" || strategy === "contains" ? 300 : 100;

  while (Date.now() - startTime < timeout) {
    // 检查暂停状态 - 如果暂停则立即停止搜索
    if (
      window.simplifiedExecutionControl &&
      window.simplifiedExecutionControl.isPaused
    ) {
      console.log("🔧 [DEBUG] 元素搜索检测到暂停状态，停止搜索");
      break;
    }

    // 检查高级引擎暂停状态
    if (window.automationEngine && window.automationEngine.isPaused) {
      console.log("🔧 [DEBUG] 元素搜索检测到高级引擎暂停状态，停止搜索");
      break;
    }

    try {
      elements = await performSingleElementSearch(strategy, value);

      // 如果找到了元素或已尝试超过一半时间，则返回结果
      if (elements.length > 0 || Date.now() - startTime > timeout / 2) {
        break;
      }
    } catch (error) {
      console.error(`查找元素时出错:`, error);
    }

    // 使用 requestAnimationFrame 或 setTimeout 让出主线程，避免阻塞
    await new Promise((resolve) => {
      if (typeof requestAnimationFrame !== "undefined") {
        requestAnimationFrame(() => setTimeout(resolve, pollingInterval));
      } else {
        setTimeout(resolve, pollingInterval);
      }
    });
  }

  console.log(
    `在 ${Date.now() - startTime}ms 内找到 ${elements.length} 个匹配元素`
  );
  return elements;
}

/**
 * 执行单次元素查找（不带轮询）
 * @param {string} strategy - 查找策略
 * @param {string} value - 查找值
 * @returns {Promise<HTMLElement[]>} - 找到的元素列表
 */
async function performSingleElementSearch(strategy, value) {
  let elements = [];

  switch (strategy) {
    case "id":
      // ID是唯一的，但为了统一处理，仍使用数组
      const idElement = document.getElementById(value);
      elements = idElement ? [idElement] : [];
      break;

    case "css":
      elements = Array.from(document.querySelectorAll(value));
      break;

    case "xpath":
      const xpathResult = document.evaluate(
        value,
        document,
        null,
        XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
        null
      );

      elements = [];
      for (let i = 0; i < xpathResult.snapshotLength; i++) {
        elements.push(xpathResult.snapshotItem(i));
      }
      break;

    case "text":
      // 精确文本匹配，使用遍历方式避免XPath转义问题
      elements = Array.from(document.querySelectorAll("*")).filter(
        (el) => el.textContent && el.textContent.trim() === value.trim()
      );
      break;

    case "contains":
      // 包含文本匹配，使用遍历方式避免XPath转义问题
      elements = Array.from(document.querySelectorAll("*")).filter(
        (el) => el.textContent && el.textContent.includes(value)
      );
      break;

    default:
      throw new Error(`不支持的定位策略: ${strategy}`);
  }

  return elements;
}

/**
 * 转义XPath字符串中的特殊字符
 * @param {string} str - 输入字符串
 * @returns {string} - 转义后的字符串
 */
function escapeXPathString(str) {
  if (str.includes('"') && str.includes("'")) {
    // 处理同时包含单引号和双引号的情况
    let parts = str.split('"');
    return `concat("${parts.join('", \'"\', "')}")`;
  }

  // 使用不存在于字符串中的引号类型
  if (str.includes('"')) {
    return `'${str}'`;
  }

  return `"${str}"`;
}

/**
 * 根据不同的定位策略查找元素
 * @param {string} strategy - 定位策略：'id', 'css', 'xpath'等
 * @param {string} selector - 对应策略的选择器
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise<HTMLElement>} - 找到的元素
 */
async function findElement(strategy, selector, timeout = 5000) {
  console.log(`尝试使用${strategy}策略查找元素: ${selector}`);
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    // 检查暂停状态
    if (
      window.simplifiedExecutionControl &&
      window.simplifiedExecutionControl.isPaused
    ) {
      console.log("🔧 [DEBUG] findElement检测到暂停状态，停止查找");
      throw new Error("查找已暂停");
    }

    if (window.automationEngine && window.automationEngine.isPaused) {
      console.log("🔧 [DEBUG] findElement检测到高级引擎暂停状态，停止查找");
      throw new Error("查找已暂停");
    }

    let element = null;

    try {
      switch (strategy) {
        case "id":
          element = document.getElementById(selector);
          break;
        case "css":
          element = document.querySelector(selector);
          break;
        default:
          throw new Error(`不支持的定位策略: ${strategy}`);
      }

      if (element) {
        console.log(`成功找到元素`, element);
        return element;
      }
    } catch (error) {
      console.error(`查找元素时出错:`, error);
    }

    // 使用异步等待避免阻塞主线程
    await new Promise((resolve) => {
      if (typeof requestAnimationFrame !== "undefined") {
        requestAnimationFrame(() => setTimeout(resolve, 100));
      } else {
        setTimeout(resolve, 100);
      }
    });
  }

  throw new Error(`超时(${timeout}ms)：无法找到元素 ${strategy}="${selector}"`);
}

/**
 * 根据精确文本内容查找元素
 * @param {string} text - 要匹配的文本
 * @param {string[]} tagNames - 要搜索的标签名列表
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise<HTMLElement>} - 找到的元素
 */
async function findElementByText(text, tagNames = ["*"], timeout = 5000) {
  console.log(`尝试根据精确文本"${text}"查找元素`);
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    // 检查暂停状态
    if (
      window.simplifiedExecutionControl &&
      window.simplifiedExecutionControl.isPaused
    ) {
      console.log("🔧 [DEBUG] findElementByText检测到暂停状态，停止查找");
      throw new Error("查找已暂停");
    }

    if (window.automationEngine && window.automationEngine.isPaused) {
      console.log(
        "🔧 [DEBUG] findElementByText检测到高级引擎暂停状态，停止查找"
      );
      throw new Error("查找已暂停");
    }

    for (const tagName of tagNames) {
      const elements = document.querySelectorAll(tagName);

      for (const element of elements) {
        if (element.textContent.trim() === text) {
          console.log(`成功根据精确文本找到元素`, element);
          return element;
        }
      }
    }

    // 使用异步等待避免阻塞主线程
    await new Promise((resolve) => {
      if (typeof requestAnimationFrame !== "undefined") {
        requestAnimationFrame(() => setTimeout(resolve, 100));
      } else {
        setTimeout(resolve, 100);
      }
    });
  }

  throw new Error(`超时(${timeout}ms)：无法找到文本为"${text}"的元素`);
}

/**
 * 根据包含的文本内容查找元素
 * @param {string} text - 要包含的文本
 * @param {string[]} tagNames - 要搜索的标签名列表
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise<HTMLElement>} - 找到的元素
 */
async function findElementContainingText(
  text,
  tagNames = ["*"],
  timeout = 5000
) {
  console.log(`尝试根据包含文本"${text}"查找元素`);
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    // 检查暂停状态
    if (
      window.simplifiedExecutionControl &&
      window.simplifiedExecutionControl.isPaused
    ) {
      throw new Error("查找已暂停");
    }

    if (window.automationEngine && window.automationEngine.isPaused) {
      throw new Error("查找已暂停");
    }

    for (const tagName of tagNames) {
      const elements = document.querySelectorAll(tagName);

      for (const element of elements) {
        if (element.textContent.includes(text)) {
          console.log(`成功根据包含文本找到元素`, element);
          return element;
        }
      }
    }

    // 使用异步等待避免阻塞主线程
    await new Promise((resolve) => {
      if (typeof requestAnimationFrame !== "undefined") {
        requestAnimationFrame(() => setTimeout(resolve, 100));
      } else {
        setTimeout(resolve, 100);
      }
    });
  }

  throw new Error(`超时(${timeout}ms)：无法找到包含文本"${text}"的元素`);
}

/**
 * 根据XPath查找元素
 * @param {string} xpath - XPath表达式
 * @param {number} timeout - 超时时间（毫秒）
 * @returns {Promise<HTMLElement>} - 找到的元素
 */
async function findElementByXPath(xpath, timeout = 5000) {
  console.log(`尝试使用XPath查找元素: ${xpath}`);
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    // 检查暂停状态
    if (
      window.simplifiedExecutionControl &&
      window.simplifiedExecutionControl.isPaused
    ) {
      console.log("🔧 [DEBUG] findElementByXPath检测到暂停状态，停止查找");
      throw new Error("查找已暂停");
    }

    if (window.automationEngine && window.automationEngine.isPaused) {
      console.log(
        "🔧 [DEBUG] findElementByXPath检测到高级引擎暂停状态，停止查找"
      );
      throw new Error("查找已暂停");
    }

    try {
      const result = document.evaluate(
        xpath,
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
      );
      const element = result.singleNodeValue;

      if (element) {
        console.log(`成功通过XPath找到元素`, element);
        return element;
      }
    } catch (error) {
      console.error(`XPath查询错误: ${error.message}`);
      return null;
    }

    // 使用异步等待避免阻塞主线程
    await new Promise((resolve) => {
      if (typeof requestAnimationFrame !== "undefined") {
        requestAnimationFrame(() => setTimeout(resolve, 100));
      } else {
        setTimeout(resolve, 100);
      }
    });
  }

  throw new Error(`超时(${timeout}ms)：无法找到元素`);
}

/**
 * 点击元素
 * @param {HTMLElement} element - 要点击的元素
 * @returns {Promise<void>}
 */
async function clickElement(element) {
  console.log(`点击元素:`, element);

  // 使用智能滚动函数，在虚拟列表模式下禁用页面滚动
  smartScrollIntoView(element, { behavior: "smooth", block: "center" });

  // 等待滚动完成
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 高亮元素以便观察
  highlightElement(element);

  try {
    // 🔧 [修复] 只使用一种点击方法，避免重复触发新窗口
    // 优先使用原生点击，如果失败再尝试事件分发
    try {
      element.click();
      console.log(`原生点击成功`);
    } catch (clickError) {
      console.log(`原生点击失败，尝试事件分发:`, clickError.message);

      // 创建并分发点击事件
      const clickEvent = new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true,
      });
      element.dispatchEvent(clickEvent);
      console.log(`事件分发点击成功`);
    }

    // 清除高亮
    setTimeout(removeHighlights, 500);

    console.log(`点击元素成功`);
    return;
  } catch (error) {
    console.error("点击元素时出错:", error);
    removeHighlights();
    throw error;
  }
}

/**
 * 在元素中输入文本
 * @param {HTMLElement} element - 要输入文本的元素
 * @param {string} text - 要输入的文本
 * @returns {Promise<void>}
 */
async function inputText(element, text) {
  console.log(`在元素中输入文本: "${text}"`, element);

  // 使用智能滚动函数，在虚拟列表模式下禁用页面滚动
  smartScrollIntoView(element, { behavior: "smooth", block: "center" });

  // 等待滚动完成
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 高亮元素以便观察
  highlightElement(element);

  try {
    // 确保元素是可输入的
    if (
      !(element instanceof HTMLInputElement) &&
      !(element instanceof HTMLTextAreaElement) &&
      element.contentEditable !== "true"
    ) {
      throw new Error("指定的元素不支持输入操作");
    }

    // 聚焦元素
    element.focus();

    // 清除现有值
    element.value = "";

    // 输入新值
    if (element.contentEditable === "true") {
      element.textContent = text;
    } else {
      element.value = text;

      // 触发input和change事件
      element.dispatchEvent(new Event("input", { bubbles: true }));
      element.dispatchEvent(new Event("change", { bubbles: true }));
    }

    // 清除高亮
    setTimeout(removeHighlights, 500);

    console.log(`文本输入成功`);
    return;
  } catch (error) {
    console.error("输入文本时出错:", error);
    removeHighlights();
    throw error;
  }
}

// 全局标志：是否在虚拟列表模式中（禁用页面滚动）
window.isVirtualListMode = false;

// 🔧 [修复] 全局停止标志，防止残留异步任务继续执行
window.globalExecutionStopped = false;

// 🔧 [修复] 新窗口去重机制 - Content Script层面
window.isCreatingNewWindow = false;
window.lastNewWindowTime = 0;
window.newWindowCooldown = 3000; // 3秒冷却时间

// 全局标志：当前窗口上下文ID（用于循环操作中的新窗口处理）
window.currentWindowContextId = null;

/**
 * 智能滚动函数 - 在虚拟列表模式下禁用页面滚动
 * @param {HTMLElement} element - 要滚动到的元素
 * @param {object} options - 滚动选项
 */
function smartScrollIntoView(
  element,
  options = { behavior: "smooth", block: "center" }
) {
  if (window.isVirtualListMode) {
    console.log(`🚫 虚拟列表模式：跳过页面滚动`);
    return;
  }

  console.log(`📍 正常模式：滚动到元素`);
  element.scrollIntoView(options);
}

/**
 * 执行通用自动化工作流
 * @param {object} workflow - 工作流配置
 * @returns {Promise<object>} - 执行结果
 */
async function executeUniversalWorkflow(workflow) {
  try {
    console.log("🚀 开始执行工作流:", workflow.name);
    return await executeSimplifiedWorkflow(workflow);
  } catch (error) {
    console.error("❌ 工作流执行失败:", error);
    throw error;
  }
}

/**
 * 根据连接关系构建正确的执行顺序
 * @param {Array} steps - 步骤数组
 * @param {Array} connections - 连接关系数组
 * @returns {Array} 按正确顺序排列的步骤数组
 */
function buildExecutionOrderSimplified(steps, connections = []) {
  console.log("🔄 开始构建执行顺序...");

  // 如果没有连接信息，按原顺序返回
  if (!connections || connections.length === 0) {
    console.log("⚠️ 没有连接信息，按原顺序执行步骤");
    return steps;
  }

  console.log(
    `📊 输入数据: ${steps.length} 个步骤, ${connections.length} 个连接`
  );

  // 创建步骤映射
  const stepMap = new Map();
  steps.forEach((step) => {
    stepMap.set(step.id, step);
  });

  // 构建邻接表（有向图）
  const graph = new Map();
  const inDegree = new Map();

  // 初始化所有节点
  steps.forEach((step) => {
    graph.set(step.id, []);
    inDegree.set(step.id, 0);
  });

  // 构建图结构
  connections.forEach((conn) => {
    if (stepMap.has(conn.source) && stepMap.has(conn.target)) {
      graph.get(conn.source).push(conn.target);
      inDegree.set(conn.target, inDegree.get(conn.target) + 1);
      console.log(
        `🔗 连接 ${stepMap.get(conn.source).name} -> ${stepMap.get(conn.target).name}`
      );
    }
  });

  // 拓扑排序找到执行顺序
  const result = [];
  const queue = [];

  // 找到所有入度为0的节点（起始节点）
  for (const [nodeId, degree] of inDegree) {
    if (degree === 0) {
      queue.push(nodeId);
      console.log(`🎯 找到起始节点: ${stepMap.get(nodeId).name}`);
    }
  }

  // 拓扑排序
  while (queue.length > 0) {
    const currentId = queue.shift();
    const currentStep = stepMap.get(currentId);

    if (currentStep) {
      result.push(currentStep);
      console.log(
        `📋 添加到执行序列: ${currentStep.name} (${currentStep.type})`
      );

      // 处理当前节点的所有邻居
      const neighbors = graph.get(currentId) || [];
      neighbors.forEach((neighborId) => {
        inDegree.set(neighborId, inDegree.get(neighborId) - 1);
        if (inDegree.get(neighborId) === 0) {
          queue.push(neighborId);
        }
      });
    }
  }

  // 检查是否有循环依赖
  if (result.length !== steps.length) {
    console.log("⚠️ 检测到循环依赖或孤立节点，添加剩余步骤");
    steps.forEach((step) => {
      if (!result.find((s) => s.id === step.id)) {
        result.push(step);
        console.log(`📋 添加孤立节点: ${step.name} (${step.type})`);
      }
    });
  }

  console.log(`✅ 执行顺序构建完成，共 ${result.length} 个步骤`);
  return result;
}

/**
 * 简化执行模式 - 当高级引擎加载失败时使用
 */
async function executeSimplifiedWorkflow(workflow) {
  console.log("🔄 开始简化执行模式");

  // 构建正确的执行顺序
  const orderedSteps = buildExecutionOrderSimplified(
    workflow.steps,
    workflow.connections
  );
  console.log(`🔄 根据连接关系构建执行顺序，共 ${orderedSteps.length} 个步骤`);

  let completedSteps = 0;
  const totalSteps = orderedSteps.length;

  // 🔧 [修复] 重置全局停止标志
  window.globalExecutionStopped = false;
  console.log(`🔧 [修复] 工作流开始，重置全局停止标志为: false`);

  // 创建执行控制对象
  window.simplifiedExecutionControl = {
    isRunning: true,
    isPaused: false,
    pausePromise: null,
    pauseResolve: null,
    currentStep: 0,
    totalSteps: totalSteps,
    completedSteps: 0,
    startTime: Date.now(),
    currentOperation: "开始执行工作流...",

    pause() {
      console.log("🔧 [DEBUG] pause() 被调用");

      // 立即设置暂停状态
      this.isPaused = true;
      console.log("🔧 [DEBUG] 暂停状态设置为:", this.isPaused);
      console.log("⏸️ 执行已暂停");

      // 立即发送暂停确认消息到浮层控制面板
      window.postMessage({
        type: 'EXECUTION_STATE_CHANGED',
        isRunning: this.isRunning,
        isPaused: this.isPaused,
        status: '工作流已暂停'
      }, '*');

      // 发送暂停确认消息到插件
      chrome.runtime
        .sendMessage({
          action: "executionPaused",
          data: { isPaused: true },
        })
        .catch((err) => console.error("发送暂停消息失败:", err));
    },

    resume() {
      console.log("🔧 [DEBUG] resume() 被调用");
      this.isPaused = false;
      console.log("🔧 [DEBUG] 暂停状态设置为:", this.isPaused);
      console.log("▶️ 继续执行");

      if (this.pauseResolve) {
        this.pauseResolve();
        this.pauseResolve = null;
        this.pausePromise = null;
      }

      // 发送继续确认消息到插件
      chrome.runtime
        .sendMessage({
          action: "executionResumed",
          data: { isPaused: false },
        })
        .catch((err) => console.error("发送继续消息失败:", err));

      // 发送恢复确认消息到浮层控制面板
      window.postMessage({
        type: 'EXECUTION_STATE_CHANGED',
        isRunning: this.isRunning,
        isPaused: this.isPaused,
        status: '已恢复执行'
      }, '*');
    },

    async checkPause() {
      console.log("🔧 [DEBUG] checkPause 被调用，当前状态:", {
        isRunning: this.isRunning,
        isPaused: this.isPaused,
        timestamp: new Date().toLocaleTimeString()
      });

      // 首先检查是否已停止
      if (!this.isRunning) {
        console.log("🔧 [DEBUG] 检测到停止状态，抛出停止信号");
        const stopError = new Error("EXECUTION_STOPPED");
        stopError.isStopSignal = true;
        throw stopError;
      }

      if (this.isPaused) {
        console.log("🔧 [DEBUG] 检测到暂停状态，开始等待...");

        // 立即发送暂停确认消息
        console.log("🔧 [DEBUG] 发送暂停确认消息到浮层");
        window.postMessage({
          type: 'EXECUTION_STATE_CHANGED',
          isRunning: this.isRunning,
          isPaused: this.isPaused,
          status: '工作流已暂停'
        }, '*');

        if (!this.pausePromise) {
          console.log("🔧 [DEBUG] 创建新的暂停Promise");
          this.pausePromise = new Promise((resolve) => {
            this.pauseResolve = resolve;
          });
        }
        console.log("🔧 [DEBUG] 等待暂停Promise解决...");
        await this.pausePromise;
        console.log("🔧 [DEBUG] 暂停Promise已解决，继续执行");

        // 暂停解除后再次检查是否已停止
        if (!this.isRunning) {
          console.log("🔧 [DEBUG] 暂停解除后检测到停止状态，抛出停止信号");
          const stopError = new Error("EXECUTION_STOPPED");
          stopError.isStopSignal = true;
          throw stopError;
        }
      }
    },

    updateProgress(stepIndex, operation) {
      this.currentStep = stepIndex;
      this.completedSteps = stepIndex;
      if (operation) {
        this.currentOperation = operation;
      }
      console.log("🔧 [DEBUG] 更新执行进度:", {
        currentStep: this.currentStep,
        completedSteps: this.completedSteps,
        currentOperation: this.currentOperation,
      });
    },

    stop() {
      console.log("🔧 [DEBUG] 停止被调用");
      this.isRunning = false;
      this.isPaused = false;
      this.currentOperation = "执行已停止";

      // 解决暂停Promise，让等待的代码继续执行并检查停止状态
      if (this.pauseResolve) {
        this.pauseResolve();
        this.pausePromise = null;
        this.pauseResolve = null;
      }

      // 发送停止确认消息
      chrome.runtime
        .sendMessage({
          action: "executionStopped",
          data: { isRunning: false, isStopped: true },
        })
        .catch((err) => console.error("发送停止消息失败:", err));
    },

    // 添加日志方法
    addLog(message, type = 'info') {
      console.log(`📋 日志: [${type.toUpperCase()}] ${message}`);

      // 发送日志到浮层控制面板
      window.postMessage({
        type: 'EXECUTION_LOG',
        message: message,
        logType: type,
        timestamp: Date.now()
      }, '*');
    },
  };

  // 暂停检查函数
  const checkPause = () => window.simplifiedExecutionControl.checkPause();

  // 发送初始进度
  chrome.runtime.sendMessage({
    action: "executionProgress",
    data: {
      isRunning: true,
      isPaused: false,
      startTime: Date.now(),
      totalSteps: totalSteps,
      completedSteps: 0,
      currentOperation: "开始执行工作流...",
    },
  });

  try {
    // 设置整体执行超时（5分钟）
    const executionTimeout = setTimeout(() => {
      throw new Error("工作流执行超时（5分钟）");
    }, 5 * 60 * 1000);

    for (let i = 0; i < orderedSteps.length; i++) {
      // 检查是否需要暂停
      await checkPause();

      const step = orderedSteps[i];
      console.log(
        `🎯 执行步骤 ${i + 1}/${totalSteps}: ${step.name} (${step.type})`
      );

      // 更新进度
      chrome.runtime.sendMessage({
        action: "executionProgress",
        data: {
          completedSteps: i,
          currentOperation: `执行步骤: ${step.name || step.type}`,
        },
      });

      // 更新简化执行控制器的进度
      if (window.simplifiedExecutionControl) {
        window.simplifiedExecutionControl.updateProgress(
          i + 1,
          `执行步骤: ${step.name || step.type}`
        );
      }

      // 创建智能超时控制器
      const timeoutController = new SmartTimeoutController(
        30000,
        step.name || step.type
      );
      const stepTimeout = timeoutController.createTimeoutPromise();

      const stepExecution = (async () => {
        // 在正常执行开始时暂停超时
        timeoutController.pause();

        switch (step.type) {
          case "click":
            await executeClickStep(step, timeoutController);
            break;
          case "input":
            await executeInputStep(step, timeoutController);
            break;
          case "wait":
            await executeWaitStep(step, timeoutController);
            break;
          case "smartWait":
            await executeSmartWaitStep(step, timeoutController);
            break;
          case "loop":
            await executeLoopStep(step, timeoutController);
            break;
          case "condition":
            await executeConditionStep(step, timeoutController);
            break;
          case "drag":
            await executeDragStep(step, timeoutController);
            break;
          default:
            console.log(`⚠️ 跳过不支持的步骤类型: ${step.type}`);
        }

        // 执行完成后清除超时
        timeoutController.clear();
      })();

      // 在步骤执行前再次检查暂停状态
      await checkPause();

      // 等待步骤完成或超时
      await Promise.race([stepExecution, stepTimeout]);

      completedSteps++;

      // 步骤完成后立即检查暂停状态
      await checkPause();

      // 更新完成进度
      chrome.runtime.sendMessage({
        action: "executionProgress",
        data: {
          completedSteps: completedSteps,
        },
      });

      // 步骤间等待（支持暂停）
      const waitDuration = 200;
      const waitStartTime = Date.now();
      while (Date.now() - waitStartTime < waitDuration) {
        // 在等待期间检查暂停状态
        await checkPause();
        await new Promise((resolve) =>
          setTimeout(
            resolve,
            Math.min(50, waitDuration - (Date.now() - waitStartTime))
          )
        );
      }
    }

    // 清除超时
    clearTimeout(executionTimeout);
    console.log("🔧 [DEBUG] 所有步骤执行完成");

    // 发送完成消息
    chrome.runtime.sendMessage({
      action: "executionComplete",
      data: {
        successCount: completedSteps,
        errorCount: 0,
        totalSteps: totalSteps,
      },
    });

    console.log("✅ 工作流执行完成");
    return { success: true, message: "工作流执行完成" };
  } catch (error) {
    // 检查是否是停止信号
    if (error.isStopSignal) {
      console.log("✅ 执行已正常停止");

      // 发送停止完成消息
      chrome.runtime.sendMessage({
        action: "executionStopped",
        data: { message: "执行已停止" },
      });

      return { success: true, message: "执行已停止" };
    }

    console.error("❌ 工作流执行失败:", error);

    // 发送错误消息
    chrome.runtime.sendMessage({
      action: "executionError",
      data: { error: error.message },
    });

    throw error;
  } finally {
    // 标记执行完成
    if (window.simplifiedExecutionControl) {
      window.simplifiedExecutionControl.isRunning = false;
    }

    // 清理简化执行控制对象
    window.simplifiedExecutionControl = null;
    console.log("🧹 执行控制已清理");
  }
}



// 简单的步骤执行函数
async function executeClickStep(step, timeoutController = null) {
  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  if (!step.locator) {
    throw new Error("缺少定位器");
  }

  // 检查定位器的完整性
  if (!step.locator.strategy) {
    // 尝试从旧格式转换
    if (step.locator.type) {
      console.log("🔄 检测到旧格式定位器，进行转换");
      step.locator.strategy = step.locator.type;
    } else {
      throw new Error("定位器缺少策略(strategy)字段");
    }
  }

  if (!step.locator.value) {
    throw new Error("定位器缺少值(value)字段");
  }

  // 查找元素时启动超时（可能需要等待）
  if (timeoutController) {
    timeoutController.start();
  }

  const element = await findElementByStrategy(
    step.locator.strategy,
    step.locator.value
  );
  if (!element) {
    throw new Error(
      `找不到元素: ${step.locator.strategy}=${step.locator.value}`
    );
  }

  // 找到元素后暂停超时（开始正常处理）
  if (timeoutController) {
    timeoutController.pause();
  }

  // 滚动到元素位置
  console.log("🔧 [DEBUG] 滚动到目标元素");
  smartScrollIntoView(element, {
    behavior: "smooth",
    block: "center",
    inline: "center",
  });

  // 等待滚动完成
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 高亮显示元素
  console.log("🔧 [DEBUG] 高亮显示目标元素");
  highlightElement(element, "click");

  // 设置自动清除高亮
  setTimeout(() => {
    clearElementHighlight(element);
  }, 2000);

  // 检查元素是否可见和可点击
  const rect = element.getBoundingClientRect();
  const isVisible =
    rect.width > 0 &&
    rect.height > 0 &&
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= window.innerHeight &&
    rect.right <= window.innerWidth;

  console.log("🔧 [DEBUG] 元素可见性检查:", {
    isVisible,
    rect: {
      width: rect.width,
      height: rect.height,
      top: rect.top,
      left: rect.left,
    },
  });

  // 执行点击
  console.log("🔧 [DEBUG] 执行点击操作");
  element.click();

  // 等待点击效果
  await new Promise((resolve) => setTimeout(resolve, 200));

  console.log(`✅ 点击元素完成: ${step.locator.value}`);
}

async function executeInputStep(step, timeoutController = null) {
  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  const text = step.text || step.inputText || "";

  if (!step.locator) {
    throw new Error("缺少定位器");
  }

  console.log("🔧 [DEBUG] 查找输入元素:", step.locator);

  // 检查定位器的完整性
  if (!step.locator.strategy) {
    // 尝试从旧格式转换
    if (step.locator.type) {
      console.log("🔄 检测到旧格式定位器，进行转换");
      step.locator.strategy = step.locator.type;
    } else {
      throw new Error("定位器缺少策略(strategy)字段");
    }
  }

  if (!step.locator.value) {
    throw new Error("定位器缺少值(value)字段");
  }

  const element = await findElementByStrategy(
    step.locator.strategy,
    step.locator.value
  );
  if (!element) {
    throw new Error(
      `找不到元素: ${step.locator.strategy}=${step.locator.value}`
    );
  }

  console.log("🔧 [DEBUG] 找到输入元素，准备输入文本:", text);
  console.log("🔧 [DEBUG] 输入元素信息:", {
    tagName: element.tagName,
    type: element.type,
    id: element.id,
    className: element.className,
  });

  // 滚动到元素位置
  console.log("🔧 [DEBUG] 滚动到输入元素");
  smartScrollIntoView(element, {
    behavior: "smooth",
    block: "center",
    inline: "center",
  });

  // 等待滚动完成
  await new Promise((resolve) => setTimeout(resolve, 300));

  // 高亮显示元素
  console.log("🔧 [DEBUG] 高亮显示输入元素");
  highlightElement(element, "input");

  // 设置自动清除高亮
  setTimeout(() => {
    clearElementHighlight(element);
  }, 2000);

  // 聚焦元素
  element.focus();

  // 清空现有内容（如果需要）
  if (step.clearFirst !== false) {
    element.value = "";
  }

  // 输入文本
  console.log("🔧 [DEBUG] 执行文本输入");
  element.value = text;

  // 触发输入事件
  element.dispatchEvent(new Event("input", { bubbles: true }));
  element.dispatchEvent(new Event("change", { bubbles: true }));

  // 等待输入效果
  await new Promise((resolve) => setTimeout(resolve, 200));

  console.log(`✅ 输入文本完成: "${text}"`);
}

async function executeWaitStep(step, timeoutController = null) {
  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  const duration = step.duration || step.waitTime || 1000;
  console.log(`⏳ 等待 ${duration}ms`);

  // 在等待过程中也要支持暂停
  const startTime = Date.now();
  while (Date.now() - startTime < duration) {
    // 每100ms检查一次暂停状态
    if (window.simplifiedExecutionControl) {
      await window.simplifiedExecutionControl.checkPause();
    }
    await new Promise((resolve) =>
      setTimeout(resolve, Math.min(100, duration - (Date.now() - startTime)))
    );
  }

  console.log(`✅ 等待完成`);
}

async function executeSmartWaitStep(step, timeoutController = null) {
  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  if (!step.locator) {
    throw new Error("等待属性缺少定位器");
  }

  console.log("🔧 [DEBUG] 等待属性定位器:", step.locator);

  // 检查定位器的完整性
  if (!step.locator.strategy) {
    // 尝试从旧格式转换
    if (step.locator.type) {
      console.log("🔄 检测到旧格式等待属性定位器，进行转换");
      step.locator.strategy = step.locator.type;
    } else {
      throw new Error("等待属性定位器缺少策略(strategy)字段");
    }
  }

  if (!step.locator.value) {
    throw new Error("等待属性定位器缺少值(value)字段");
  }

  const timeout = step.timeout || 30000;
  const checkInterval = step.checkInterval || 500;
  const attributeName = step.attributeName || "";
  const comparisonType = step.comparisonType || "equals";
  const expectedValue = step.expectedValue || "";

  if (!attributeName) {
    throw new Error("等待属性缺少属性名称");
  }

  console.log(
    `🔍 等待属性: ${attributeName} ${comparisonType} "${expectedValue}" - ${step.locator.strategy}=${step.locator.value}, 超时: ${timeout}ms`
  );
  console.log(
    `⚙️ 属性条件: ${attributeName} ${comparisonType} "${expectedValue}"`
  );

  // 智能等待时启动超时（正在等待元素出现）
  if (timeoutController) {
    timeoutController.start();
  }

  const startTime = Date.now();
  while (Date.now() - startTime < timeout) {
    // 检查暂停状态
    if (window.simplifiedExecutionControl) {
      await window.simplifiedExecutionControl.checkPause();
    }

    try {
      const conditionMet = await checkAttributeConditionSimplified(
        step.locator,
        attributeName,
        comparisonType,
        expectedValue
      );
      if (conditionMet) {
        console.log(
          `✅ 等待属性成功: ${attributeName} ${comparisonType} "${expectedValue}"`
        );
        // 找到元素后暂停超时
        if (timeoutController) {
          timeoutController.pause();
        }
        return;
      }
    } catch (error) {
      // 如果是暂停导致的错误，重新抛出
      if (error.message === "查找已暂停") {
        throw error;
      }
      // 其他错误（包括超时）继续等待
    }

    // 使用异步等待避免阻塞主线程
    await new Promise((resolve) => {
      if (typeof requestAnimationFrame !== "undefined") {
        requestAnimationFrame(() => setTimeout(resolve, checkInterval));
      } else {
        setTimeout(resolve, checkInterval);
      }
    });
  }

  throw new Error(
    `等待属性超时: ${attributeName} ${comparisonType} "${expectedValue}" 未在 ${timeout}ms 内满足`
  );
}

/**
 * 获取等待条件的描述（简化版）
 */
function getWaitConditionDescription(waitCondition) {
  switch (waitCondition) {
    case "appear":
      return "元素出现";
    case "disappear":
      return "元素消失";
    case "visible":
      return "元素可见";
    case "hidden":
      return "元素隐藏";
    case "attributeAppear":
      return "属性出现";
    default:
      return "元素出现";
  }
}

/**
 * 检查属性条件是否满足（简化版）
 */
async function checkAttributeConditionSimplified(
  locator,
  attributeName,
  comparisonType,
  expectedValue
) {
  try {
    const element = await findElementByStrategy(
      locator.strategy,
      locator.value,
      100
    );

    if (!element) {
      return false;
    }

    // 获取属性值
    const actualValue = element.getAttribute(attributeName);

    // 如果属性不存在，返回false
    if (actualValue === null) {
      return false;
    }

    // 根据比较方式进行判断
    switch (comparisonType) {
      case "equals":
        return actualValue === expectedValue;
      case "contains":
        return actualValue.includes(expectedValue);
      default:
        return actualValue === expectedValue;
    }
  } catch (error) {
    return false;
  }
}

/**
 * 测试属性条件
 */
async function testAttributeCondition(data) {
  try {
    const { locator, attributeName, comparisonType, expectedValue } = data;

    if (!locator || !attributeName) {
      return {
        success: false,
        error: "缺少必要的参数",
      };
    }

    // 查找元素
    const element = await findElementByStrategy(
      locator.strategy,
      locator.value
    );

    if (!element) {
      return {
        success: true,
        conditionMet: false,
        message: `找不到元素: ${locator.strategy}=${locator.value}`,
      };
    }

    // 高亮显示元素
    highlightElement(element, "testing");

    // 获取属性值
    const actualValue = element.getAttribute(attributeName);

    if (actualValue === null) {
      return {
        success: true,
        conditionMet: false,
        message: `元素不存在属性: ${attributeName}`,
      };
    }

    // 检查条件
    let conditionMet = false;
    switch (comparisonType) {
      case "equals":
        conditionMet = actualValue === expectedValue;
        break;
      case "contains":
        conditionMet = actualValue.includes(expectedValue);
        break;
      default:
        conditionMet = actualValue === expectedValue;
    }

    const message = conditionMet
      ? `属性条件满足: ${attributeName}="${actualValue}" ${comparisonType} "${expectedValue}"`
      : `属性条件不满足: ${attributeName}="${actualValue}" ${comparisonType} "${expectedValue}"`;

    // 清除高亮
    setTimeout(() => {
      clearElementHighlight(element);
    }, 3000);

    return {
      success: true,
      conditionMet,
      message,
      actualValue,
    };
  } catch (error) {
    console.error("测试属性条件失败:", error);
    return {
      success: false,
      error: error.message,
    };
  }
}

/**
 * 检查元素是否可见（简化版）
 */
function isElementVisibleSimplified(element) {
  if (!element) return false;

  // 方法1：检查offsetParent（最常用的可见性检查）
  if (element.offsetParent === null) {
    // 进一步检查是否是因为position:fixed而导致offsetParent为null
    const style = getComputedStyle(element);
    if (style.position !== "fixed") {
      return false;
    }
  }

  // 方法2：检查display和visibility
  const style = getComputedStyle(element);
  if (style.display === "none" || style.visibility === "hidden") {
    return false;
  }

  // 方法3：检查opacity
  if (parseFloat(style.opacity) === 0) {
    return false;
  }

  // 方法4：检查尺寸
  const rect = element.getBoundingClientRect();
  if (rect.width === 0 && rect.height === 0) {
    return false;
  }

  return true;
}

// 执行拖拽步骤
async function executeDragStep(step, timeoutController = null) {
  console.log("🔧 [DEBUG] executeDragStep 开始执行");

  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  if (!step.locator) {
    throw new Error("拖拽步骤缺少定位器配置");
  }

  console.log("🔧 [DEBUG] 拖拽定位器:", step.locator);
  console.log("🔧 [DEBUG] 拖拽距离:", {
    horizontal: step.horizontalDistance || 0,
    vertical: step.verticalDistance || 0,
  });

  // 查找目标元素
  const element = await findElementByStrategy(
    step.locator.strategy,
    step.locator.value
  );
  if (!element) {
    throw new Error(
      `找不到拖拽目标元素: ${step.locator.strategy}=${step.locator.value}`
    );
  }

  // 找到元素后暂停超时（开始正常处理）
  if (timeoutController) {
    timeoutController.pause();
  }

  console.log("🔧 [DEBUG] 找到拖拽目标元素，准备执行拖拽操作");

  // 滚动到元素位置
  smartScrollIntoView(element, {
    behavior: "smooth",
    block: "center",
    inline: "center",
  });

  // 等待滚动完成
  await new Promise((resolve) => setTimeout(resolve, 500));

  // 高亮显示元素
  highlightElement(element, "drag");

  // 获取元素的中心位置
  const rect = element.getBoundingClientRect();
  const startX = rect.left + rect.width / 2;
  const startY = rect.top + rect.height / 2;

  // 计算目标位置
  const horizontalDistance = step.horizontalDistance || 0;
  const verticalDistance = step.verticalDistance || 0;
  const endX = startX + horizontalDistance;
  const endY = startY + verticalDistance;

  console.log(`🖱️ 拖拽路径: (${startX}, ${startY}) -> (${endX}, ${endY})`);

  // 执行拖拽操作
  await performDragOperation(element, startX, startY, endX, endY, step);

  // 清除高亮
  setTimeout(() => {
    clearElementHighlight(element);
  }, 2000);

  console.log(
    `✅ 拖拽操作完成: 水平${horizontalDistance}px, 垂直${verticalDistance}px`
  );
}

// 执行增强的拖拽操作（支持HTML5拖拽元素）
async function performEnhancedDragOperation(
  element,
  startX,
  startY,
  endX,
  endY,
  step
) {
  const dragSpeed = step.dragSpeed || 100;
  const waitAfterDrag = step.waitAfterDrag || 1000;

  console.log("🖱️ 开始增强拖拽操作");

  // 方法1: 尝试直接移动元素位置
  const originalPosition = element.style.position;
  const originalLeft = element.style.left;
  const originalTop = element.style.top;
  const originalTransform = element.style.transform;

  try {
    // 设置元素为相对定位以便移动
    if (!originalPosition || originalPosition === "static") {
      element.style.position = "relative";
    }

    // 计算移动距离
    const deltaX = endX - startX;
    const deltaY = endY - startY;

    console.log(`🖱️ 移动元素: deltaX=${deltaX}px, deltaY=${deltaY}px`);

    // 添加移动动画
    element.style.transition = `transform ${dragSpeed}ms ease-out`;
    element.style.transform = `translate(${deltaX}px, ${deltaY}px)`;

    // 等待动画完成
    await new Promise((resolve) => setTimeout(resolve, dragSpeed));

    // 触发拖拽事件以确保兼容性
    const dragStartEvent = new DragEvent("dragstart", {
      bubbles: true,
      cancelable: true,
      clientX: startX,
      clientY: startY,
    });
    element.dispatchEvent(dragStartEvent);

    await new Promise((resolve) => setTimeout(resolve, 100));

    const dragEndEvent = new DragEvent("dragend", {
      bubbles: true,
      cancelable: true,
      clientX: endX,
      clientY: endY,
    });
    element.dispatchEvent(dragEndEvent);

    console.log("🖱️ 增强拖拽操作完成");

    // 等待指定时间后恢复原始状态
    await new Promise((resolve) => setTimeout(resolve, waitAfterDrag));

    // 恢复原始样式
    element.style.transition = "";
    element.style.transform = originalTransform;
    element.style.position = originalPosition;
    element.style.left = originalLeft;
    element.style.top = originalTop;
  } catch (error) {
    console.error("🖱️ 增强拖拽操作失败:", error);
    // 恢复原始样式
    element.style.transition = "";
    element.style.transform = originalTransform;
    element.style.position = originalPosition;
    element.style.left = originalLeft;
    element.style.top = originalTop;
    throw error;
  }
}

// 执行具体的拖拽操作
async function performDragOperation(element, startX, startY, endX, endY, step) {
  const dragSpeed = step.dragSpeed || 100;
  const waitAfterDrag = step.waitAfterDrag || 1000;

  // 1. 触发 mousedown 事件
  const mouseDownEvent = new MouseEvent("mousedown", {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: startX,
    clientY: startY,
    button: 0,
    buttons: 1,
  });
  element.dispatchEvent(mouseDownEvent);
  console.log("🖱️ 已触发 mousedown 事件");

  // 等待一小段时间
  await new Promise((resolve) => setTimeout(resolve, dragSpeed));

  // 2. 触发 mousemove 事件（分步移动以模拟真实拖拽）
  const distance = Math.max(Math.abs(endX - startX), Math.abs(endY - startY));
  const steps = Math.min(Math.max(Math.floor(distance / 10), 1), 20); // 限制步数在1-20之间

  for (let i = 1; i <= steps; i++) {
    const progress = i / steps;
    const currentX = startX + (endX - startX) * progress;
    const currentY = startY + (endY - startY) * progress;

    const mouseMoveEvent = new MouseEvent("mousemove", {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: currentX,
      clientY: currentY,
      button: 0,
      buttons: 1,
    });

    // 在document上触发mousemove事件
    document.dispatchEvent(mouseMoveEvent);

    // 短暂等待以模拟真实拖拽速度
    await new Promise((resolve) => setTimeout(resolve, dragSpeed / steps));
  }

  console.log("🖱️ 已完成 mousemove 事件序列");

  // 3. 触发 mouseup 事件
  const mouseUpEvent = new MouseEvent("mouseup", {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: endX,
    clientY: endY,
    button: 0,
    buttons: 0,
  });
  document.dispatchEvent(mouseUpEvent);
  console.log("🖱️ 已触发 mouseup 事件");

  // 等待拖拽完成
  await new Promise((resolve) => setTimeout(resolve, waitAfterDrag));
}

// 执行条件判断步骤
async function executeConditionStep(step, timeoutController = null) {
  console.log(`🧪 执行条件判断步骤:`, step);

  const locator = step.locator;
  if (!locator) {
    throw new Error("条件判断步骤缺少定位器配置");
  }

  console.log("🔧 [DEBUG] 条件判断定位器:", locator);

  // 检查定位器的完整性
  if (!locator.strategy) {
    // 尝试从旧格式转换
    if (locator.type) {
      console.log("🔄 检测到旧格式条件定位器，进行转换");
      locator.strategy = locator.type;
    } else {
      throw new Error("条件判断定位器缺少策略(strategy)字段");
    }
  }

  if (!locator.value) {
    throw new Error("条件判断定位器缺少值(value)字段");
  }

  // 查找元素
  const element = findSingleElement(locator.strategy, locator.value);
  if (!element) {
    throw new Error(
      `条件判断失败: 找不到元素 (${locator.strategy}: ${locator.value})`
    );
  }

  // 高亮元素
  highlightElement(element, "processing");

  // 执行条件判断
  let conditionResult = false;
  let actualValue = "";
  const expectedValue = step.expectedValue || "";
  const attributeName = step.attributeName || "";

  try {
    // 获取实际值
    switch (step.conditionType) {
      case "attribute":
        actualValue = element.getAttribute(attributeName) || "";
        break;
      case "text":
        actualValue = element.textContent || "";
        break;
      case "class":
        // 安全地获取className，处理SVG元素
        try {
          if (typeof element.className === "string") {
            actualValue = element.className;
          } else if (
            element.className &&
            element.className.baseVal !== undefined
          ) {
            actualValue = element.className.baseVal;
          } else {
            actualValue = "";
          }
        } catch (error) {
          actualValue = "";
        }
        break;
      case "style":
        actualValue = getComputedStyle(element)[attributeName] || "";
        break;
      case "value":
        actualValue = element.value || "";
        break;
      case "exists":
        conditionResult = true; // 元素已找到
        break;
      case "visible":
        conditionResult = element.offsetParent !== null;
        break;
    }

    // 执行比较
    if (step.conditionType !== "exists" && step.conditionType !== "visible") {
      switch (step.comparisonType) {
        case "equals":
          conditionResult = actualValue === expectedValue;
          break;
        case "notEquals":
          conditionResult = actualValue !== expectedValue;
          break;
        case "contains":
          conditionResult = actualValue.includes(expectedValue);
          break;
        case "notContains":
          conditionResult = !actualValue.includes(expectedValue);
          break;
        case "startsWith":
          conditionResult = actualValue.startsWith(expectedValue);
          break;
        case "endsWith":
          conditionResult = actualValue.endsWith(expectedValue);
          break;
        case "isEmpty":
          conditionResult = actualValue === "";
          break;
        case "isNotEmpty":
          conditionResult = actualValue !== "";
          break;
        case "hasAttribute":
          conditionResult = element.hasAttribute(attributeName);
          break;
        case "notHasAttribute":
          conditionResult = !element.hasAttribute(attributeName);
          break;
      }
    }

    // 显示结果
    if (conditionResult) {
      highlightElement(element, "success");
      console.log(
        `✅ 条件判断通过: ${step.conditionType} ${step.comparisonType} "${expectedValue}" (实际值: "${actualValue}")`
      );
    } else {
      highlightElement(element, "error");
      console.log(
        `❌ 条件判断失败: ${step.conditionType} ${step.comparisonType} "${expectedValue}" (实际值: "${actualValue}")`
      );
      throw new Error(
        `条件判断失败: 期望 ${step.conditionType} ${step.comparisonType} "${expectedValue}"，实际值为 "${actualValue}"`
      );
    }

    // 等待一下让用户看到结果
    await new Promise((resolve) => setTimeout(resolve, 1000));
  } catch (error) {
    highlightElement(element, "error");
    throw error;
  }
}

async function executeLoopStep(step, timeoutController = null) {
  // 在执行循环步骤前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  if (!step.locator) {
    throw new Error("缺少循环定位器");
  }

  // 检查定位器的完整性
  if (!step.locator.strategy) {
    // 尝试从旧格式转换
    if (step.locator.type) {
      step.locator.strategy = step.locator.type;
    } else {
      throw new Error("循环定位器缺少策略(strategy)字段");
    }
  }

  if (!step.locator.value) {
    throw new Error("循环定位器缺少值(value)字段");
  }

  // 查找元素时启动超时（可能需要等待）
  if (timeoutController) {
    timeoutController.start();
  }

  const elements = await findElementsByStrategy(
    step.locator.strategy,
    step.locator.value
  );
  if (elements.length === 0) {
    throw new Error(
      `找不到循环元素: ${step.locator.strategy}=${step.locator.value}`
    );
  }

  // 找到元素后暂停超时（开始正常处理）
  if (timeoutController) {
    timeoutController.pause();
  }

  const startIndex = step.startIndex || 0;
  const endIndex =
    step.endIndex === -1
      ? elements.length - 1
      : step.endIndex || elements.length - 1;
  const actualEndIndex = Math.min(endIndex, elements.length - 1);

  // 检查是否为虚拟列表模式

  if (step.isVirtualList) {
    console.log(`📜 检测到虚拟列表模式，开始智能遍历`);
    // 设置虚拟列表模式标志，禁用页面滚动
    isVirtualListMode = true;
    try {
      await executeVirtualListLoop(step);
    } finally {
      // 执行完成后重置标志
      isVirtualListMode = false;
      console.log(`📜 虚拟列表模式结束，恢复页面滚动`);
    }
    return;
  }

  console.log(
    `🔄 开始执行${step.loopType}循环: ${elements.length} 个元素，范围 ${startIndex}-${actualEndIndex}`
  );

  for (let i = startIndex; i <= actualEndIndex; i++) {
    // 在每个循环迭代前检查暂停状态
    if (window.simplifiedExecutionControl) {
      await window.simplifiedExecutionControl.checkPause();
    }

    const element = elements[i];
    console.log(`🎯 处理第 ${i + 1}/${elements.length} 个元素`);

    // 敏感词检测
    if (step.sensitiveWordDetection && step.sensitiveWordDetection.enabled) {
      try {
        console.log(`🔍 敏感词检测 - 第 ${i + 1} 个元素`);

        // 创建敏感词检测器实例
        const detector = new window.SensitiveWordDetector();

        // 检查是否应该跳过当前元素
        const skipResult = await detector.checkShouldSkipElement(
          element,
          step.sensitiveWordDetection
        );

        if (skipResult.shouldSkip) {
          console.log(`🚫 跳过第 ${i + 1} 个元素: ${skipResult.reason}`);

          // 添加到日志显示
          if (window.simplifiedExecutionControl) {
            window.simplifiedExecutionControl.addLog(
              `🚫 跳过第 ${i + 1} 个元素: ${skipResult.reason}`,
              'warning'
            );
          }

          // 高亮显示被跳过的元素
          highlightElement(element, "skip");
          setTimeout(() => {
            clearElementHighlight(element);
          }, 1500);

          // 跳过当前循环，继续下一个
          continue;
        } else {
          console.log(`✅ 第 ${i + 1} 个元素通过敏感词检测`);
        }
      } catch (error) {
        console.error(`❌ 敏感词检测失败 - 第 ${i + 1} 个元素:`, error);
        // 检测失败时继续执行，避免影响正常流程
      }
    }

    // 记录当前页面滚动位置
    const scrollBefore = {
      x: window.pageXOffset || document.documentElement.scrollLeft,
      y: window.pageYOffset || document.documentElement.scrollTop,
    };
    console.log("🔧 [DEBUG] 操作前页面滚动位置:", scrollBefore);

    try {
      if (step.loopType === "simpleLoop") {
        // 简单循环：执行单一操作
        await executeSimpleLoopAction(element, step);
      } else if (step.loopType === "container") {
        // 容器循环：直接在容器内执行子操作，不点击容器本身
        await executeContainerLoopAction(element, step);
      } else {
        // 父级循环：点击后执行子操作
        await executeParentLoopAction(element, step);
      }

      // 记录操作后的滚动位置
      const scrollAfter = {
        x: window.pageXOffset || document.documentElement.scrollLeft,
        y: window.pageYOffset || document.documentElement.scrollTop,
      };
      console.log("🔧 [DEBUG] 操作后页面滚动位置:", scrollAfter);

      if (
        scrollBefore.y !== scrollAfter.y ||
        scrollBefore.x !== scrollAfter.x
      ) {
        console.log("✅ 页面滚动已发生，滚动距离:", {
          deltaX: scrollAfter.x - scrollBefore.x,
          deltaY: scrollAfter.y - scrollBefore.y,
        });
      }

      // 循环间隔（支持暂停）
      if (step.loopDelay) {
        console.log(`🔧 [DEBUG] 循环延迟开始: ${step.loopDelay}ms`);
        const delayStartTime = Date.now();
        while (Date.now() - delayStartTime < step.loopDelay) {
          // 在延迟期间检查暂停状态
          if (window.simplifiedExecutionControl) {
            await window.simplifiedExecutionControl.checkPause();
          }
          await new Promise((resolve) =>
            setTimeout(
              resolve,
              Math.min(100, step.loopDelay - (Date.now() - delayStartTime))
            )
          );
        }
        console.log(`🔧 [DEBUG] 循环延迟完成`);
      }
    } catch (error) {
      console.error(`❌ 第 ${i + 1} 个元素处理失败:`, error);
      if (step.errorHandling === "stop") {
        throw error;
      }
    }
  }

  console.log(`✅ 循环执行完成`);
}

async function executeSimpleLoopAction(element, step) {
  console.log("🔧 [DEBUG] executeSimpleLoopAction 开始执行");

  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  const actionType = step.actionType || "click";
  console.log(`🔧 执行简单操作: ${actionType}`);

  switch (actionType) {
    case "click":
      console.log(`🔧 [DEBUG] 准备点击循环元素`);
      console.log("🔧 [DEBUG] 循环元素信息:", {
        tagName: element.tagName,
        id: element.id,
        className: element.className,
        textContent: element.textContent?.substring(0, 50) + "...",
      });

      // 滚动到元素位置
      console.log("🔧 [DEBUG] 滚动到循环目标元素");
      smartScrollIntoView(element, {
        behavior: "smooth",
        block: "center",
        inline: "center",
      });

      // 等待滚动完成
      await new Promise((resolve) => setTimeout(resolve, 300));

      // 高亮显示元素
      console.log("🔧 [DEBUG] 高亮显示循环目标元素");
      highlightElement(element, "loop");

      // 设置自动清除高亮
      setTimeout(() => {
        clearElementHighlight(element);
      }, 1500);

      // 检查元素可见性
      const rect = element.getBoundingClientRect();
      const isVisible = rect.width > 0 && rect.height > 0;
      console.log("🔧 [DEBUG] 循环元素可见性:", {
        isVisible,
        rect: {
          width: rect.width,
          height: rect.height,
          top: rect.top,
          left: rect.left,
        },
      });

      // 执行点击
      console.log("🔧 [DEBUG] 执行循环元素点击");
      element.click();

      // 等待点击效果
      await new Promise((resolve) => setTimeout(resolve, 200));

      console.log(`👆 循环点击元素完成`);
      break;
    case "input":
      const inputText = step.inputText || "";
      element.value = inputText;
      element.dispatchEvent(new Event("input", { bubbles: true }));
      element.dispatchEvent(new Event("change", { bubbles: true }));
      console.log(`⌨️ 输入文本: "${inputText}"`);
      break;
    case "check":
      if (!element.checked) {
        element.checked = true;
        element.dispatchEvent(new Event("change", { bubbles: true }));
        console.log(`☑️ 勾选复选框`);
      }
      break;
    case "uncheck":
      if (element.checked) {
        element.checked = false;
        element.dispatchEvent(new Event("change", { bubbles: true }));
        console.log(`☐ 取消勾选复选框`);
      }
      break;
    default:
      throw new Error(`不支持的简单循环操作类型: ${actionType}`);
  }

  // 操作后等待（支持暂停）
  const delay = step.operationDelay || step.actionDelay || step.loopDelay;
  if (delay) {
    console.log(`🔧 [DEBUG] 简单循环延迟开始: ${delay}ms`);
    const delayStartTime = Date.now();
    while (Date.now() - delayStartTime < delay) {
      // 在延迟期间检查暂停状态
      if (window.simplifiedExecutionControl) {
        await window.simplifiedExecutionControl.checkPause();
      }
      await new Promise((resolve) =>
        setTimeout(
          resolve,
          Math.min(100, delay - (Date.now() - delayStartTime))
        )
      );
    }
    console.log(`🔧 [DEBUG] 简单循环延迟完成`);
  }
}

async function executeContainerLoopAction(element, step) {
  console.log("🔧 [DEBUG] executeContainerLoopAction 开始执行 - 容器循环模式");

  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  console.log(`📦 开始处理容器元素，不点击容器本身`);
  console.log("🔧 [DEBUG] 容器元素信息:", {
    tagName: element.tagName,
    id: element.id,
    className: element.className,
    textContent: element.textContent?.substring(0, 50) + "...",
  });

  // 更新状态反馈 - 容器循环开始
  if (window.updateStatus) {
    const containerInfo =
      element.tagName === "BUTTON"
        ? `按钮容器: ${element.textContent?.trim() || "未知按钮"}`
        : `${element.tagName}容器: ${element.className || element.id || "未知容器"
        }`;
    window.updateStatus(`📦 处理循环容器: ${containerInfo}`, "info");
  }

  // 高亮显示容器元素
  highlightElement(element, "loop");
  setTimeout(() => {
    clearElementHighlight(element);
  }, 2000);

  // 滚动到容器元素位置，确保可见
  smartScrollIntoView(element, {
    behavior: "smooth",
    block: "center",
    inline: "center",
  });

  // 等待滚动完成
  await new Promise((resolve) => setTimeout(resolve, 300));

  // 直接执行子操作序列，不点击容器元素
  if (step.subOperations && step.subOperations.length > 0) {
    console.log(`🔧 开始在容器内执行 ${step.subOperations.length} 个子操作`);
    console.log(
      "🔧 [DEBUG] 子操作列表:",
      step.subOperations.map(
        (op, i) => `${i + 1}. ${op.type} - ${op.locator?.value || op.locator}`
      )
    );

    // 保存原始窗口上下文
    const originalWindowContext = window.currentWindowContextId;
    let isInNewWindow = false;

    for (let i = 0; i < step.subOperations.length; i++) {
      // 在每个子操作执行前检查暂停状态
      if (window.simplifiedExecutionControl) {
        await window.simplifiedExecutionControl.checkPause();
      }

      const subOp = step.subOperations[i];
      console.log(
        `🎯 执行容器内子操作 ${i + 1}: ${subOp.type} - ${subOp.locator?.value || subOp.locator
        }`
      );

      try {
        // 检查是否是会打开新窗口的操作
        const willOpenNewWindow = subOp.type === "click" && (
          subOp.opensNewWindow === true ||
          subOp.opensNewWindow === "true" ||
          (subOp.locator && typeof subOp.locator === 'object' && subOp.locator.opensNewWindow)
        );

        if (willOpenNewWindow) {
          console.log(`🪟 容器内子操作 ${i + 1} 将打开新窗口`);
        }

        // 如果当前在新窗口中，使用简化的处理方式
        if (isInNewWindow && window.currentWindowContextId) {
          console.log(`🔄 检测到新窗口上下文，处理子操作 ${i + 1}: ${subOp.type}`);

          // 对于新窗口中的操作，我们使用简化的处理方式
          if (subOp.type === "click") {
            console.log("🔄 新窗口中的点击操作：等待并跳过（因为在新窗口中）");

            // 等待一下模拟操作时间
            await new Promise(resolve => setTimeout(resolve, 1000));
            console.log(`✅ 新窗口中子操作 ${i + 1} 已跳过（模拟执行）`);

          } else if (subOp.type === "closeWindow") {
            console.log("🗑️ 新窗口中的关闭窗口操作：等待并模拟关闭");

            // 等待一下模拟关闭时间
            await new Promise(resolve => setTimeout(resolve, 1000));
            console.log(`✅ 新窗口关闭操作已模拟完成`);

            // 重置新窗口标记，表示已经回到原窗口
            isInNewWindow = false;
            window.currentWindowContextId = originalWindowContext;

          } else if (subOp.type === "wait") {
            console.log(`⏱️ 新窗口中的等待操作: ${subOp.duration || 3000}ms`);
            await new Promise(resolve => setTimeout(resolve, subOp.duration || 3000));
            console.log(`✅ 新窗口中等待操作完成`);

          } else {
            // 其他操作也跳过
            console.log(`🔄 新窗口中的${subOp.type}操作：跳过执行`);
            await new Promise(resolve => setTimeout(resolve, 500));
            console.log(`✅ 新窗口中子操作 ${i + 1} 已跳过`);
          }
        } else {
          // 在当前窗口中执行操作
          // 传递容器元素上下文给子操作
          await executeSubOperation(subOp, element);

          // 如果操作打开了新窗口，检查是否需要切换窗口上下文
          if (willOpenNewWindow && !isInNewWindow) {
            console.log(`🔄 容器内操作打开新窗口，检查窗口上下文切换`);

            // 等待一下让新窗口完全加载
            await new Promise(resolve => setTimeout(resolve, 2000));

            // 检查是否已经切换到新窗口
            if (window.currentWindowContextId && window.currentWindowContextId !== originalWindowContext) {
              isInNewWindow = true;
              console.log(`✅ 容器内已切换到新窗口上下文: ${window.currentWindowContextId}`);
            } else {
              console.log(`⚠️ 容器内新窗口上下文未更新，但新窗口已打开`);
              console.log(`🔄 设置新窗口标记，后续操作将跳过或使用替代方案`);
              isInNewWindow = true; // 强制设置为true，因为我们知道新窗口已经打开了
              window.currentWindowContextId = Date.now(); // 设置一个模拟的窗口ID
            }
          }
        }

      } catch (error) {
        // 如果是停止信号，直接重新抛出
        if (error.isStopSignal || error.message === 'EXECUTION_STOPPED') {
          console.log(`🛑 容器内子操作 ${i + 1} 收到停止信号，停止执行`);
          throw error;
        }

        console.error(`❌ 容器内子操作 ${i + 1} 失败:`, error);
        if (step.errorHandling === "stop") {
          throw error;
        }
      }

      // 子操作间等待
      if (subOp.delay || subOp.waitAfterClick) {
        const waitTime = subOp.delay || subOp.waitAfterClick || 500;
        console.log(`⏳ 子操作间等待 ${waitTime}ms`);

        // 在等待过程中支持暂停检查
        const delayStartTime = Date.now();
        while (Date.now() - delayStartTime < waitTime) {
          // 每100ms检查一次暂停状态
          if (window.simplifiedExecutionControl) {
            await window.simplifiedExecutionControl.checkPause();
          }
          await new Promise((resolve) =>
            setTimeout(resolve, Math.min(100, waitTime - (Date.now() - delayStartTime)))
          );
        }
      }
    }

    console.log(`✅ 容器内所有子操作执行完成`);

    // 重置窗口上下文，确保后续操作在正确的窗口中执行
    if (isInNewWindow) {
      console.log("🔄 容器内操作在新窗口中完成，重置窗口上下文");
      window.currentWindowContextId = originalWindowContext;
    } else {
      window.currentWindowContextId = null;
    }
    console.log("🔄 重置窗口上下文");
  } else {
    console.log(`📦 容器循环没有配置子操作，执行直接操作`);

    // 获取操作类型
    const actionType = step.actionType || step.operationType || "click";
    console.log(`🔧 执行操作类型: ${actionType}`);

    // 执行指定的操作
    switch (actionType) {
      case "click":
        element.click();
        console.log(`👆 已点击容器元素`);
        break;
      case "input":
        if (step.inputText) {
          element.value = step.inputText;
          element.dispatchEvent(new Event("input", { bubbles: true }));
          element.dispatchEvent(new Event("change", { bubbles: true }));
          console.log(`📝 已输入文本: ${step.inputText}`);
        }
        break;
      case "hover":
        element.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
        console.log(`🖱️ 已悬停元素`);
        break;
      default:
        console.log(`⚠️ 不支持的操作类型: ${actionType}`);
    }
  }

  // 操作延迟
  if (step.operationDelay) {
    console.log(`🔧 [DEBUG] 容器操作延迟开始: ${step.operationDelay}ms`);
    const delayStartTime = Date.now();
    while (Date.now() - delayStartTime < step.operationDelay) {
      // 在延迟期间检查暂停状态
      if (window.simplifiedExecutionControl) {
        await window.simplifiedExecutionControl.checkPause();
      }
      await new Promise((resolve) =>
        setTimeout(
          resolve,
          Math.min(100, step.operationDelay - (Date.now() - delayStartTime))
        )
      );
    }
    console.log(`🔧 [DEBUG] 容器操作延迟完成`);
  }
}

async function executeParentLoopAction(element, step) {
  console.log("🔧 [DEBUG] executeParentLoopAction 开始执行");

  // 在执行具体操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  console.log(`🎯 开始处理父级元素`);

  // 1. 点击父级元素
  console.log(`🔧 [DEBUG] 准备点击父级元素`);
  element.click();
  console.log(`👆 已点击父级元素`);

  // 2. 等待页面响应
  if (step.waitAfterClick) {
    console.log(`⏳ 等待页面响应 ${step.waitAfterClick}ms`);
    await new Promise((resolve) => setTimeout(resolve, step.waitAfterClick));
  }

  // 3. 执行子操作序列
  if (step.subOperations && step.subOperations.length > 0) {
    console.log(`🔧 开始执行 ${step.subOperations.length} 个子操作`);

    for (let i = 0; i < step.subOperations.length; i++) {
      // 在每个子操作执行前检查暂停状态
      if (window.simplifiedExecutionControl) {
        await window.simplifiedExecutionControl.checkPause();
      }

      const subOp = step.subOperations[i];
      console.log(
        `🎯 执行子操作 ${i + 1}: ${subOp.type} - ${subOp.locator?.value || subOp.locator
        }`
      );

      try {
        // 传递父级元素上下文给子操作
        await executeSubOperation(subOp, element);
      } catch (error) {
        // 如果是停止信号，直接重新抛出
        if (error.isStopSignal || error.message === 'EXECUTION_STOPPED') {
          console.log(`🛑 子操作 ${i + 1} 收到停止信号，停止执行`);
          throw error;
        }

        console.error(`❌ 子操作 ${i + 1} 失败:`, error);
        if (step.errorHandling === "stop") {
          throw error;
        }
      }

      // 子操作间等待
      if (subOp.delay) {
        // 在等待过程中支持暂停检查
        const delayStartTime = Date.now();
        while (Date.now() - delayStartTime < subOp.delay) {
          // 每100ms检查一次暂停状态
          if (window.simplifiedExecutionControl) {
            await window.simplifiedExecutionControl.checkPause();
          }
          await new Promise((resolve) =>
            setTimeout(resolve, Math.min(100, subOp.delay - (Date.now() - delayStartTime)))
          );
        }
      }
    }

    console.log(`✅ 所有子操作执行完成`);

    // 重置窗口上下文，确保后续操作在正确的窗口中执行
    window.currentWindowContextId = null;
    console.log("🔄 重置窗口上下文");
  }

  // 4. 父级循环操作延迟
  const delay = step.operationDelay || step.loopDelay || step.actionDelay;
  if (delay) {
    console.log(`⏳ 父级循环延迟 ${delay}ms`);
    await new Promise((resolve) => setTimeout(resolve, delay));
    console.log(`✅ 父级循环延迟完成`);
  }
}

async function executeSubOperation(operation, parentElement = null) {
  // 在执行任何子操作前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  console.log(`🔍 执行子操作: ${operation.type}`, operation.locator);

  // 检查是否需要更新窗口上下文（处理循环中的新窗口操作）
  if (window.currentWindowContextId) {
    console.log(`🔄 当前窗口上下文ID: ${window.currentWindowContextId}`);
    // 这里可以添加窗口上下文验证逻辑
  }

  switch (operation.type) {
    case "click":
      let clickElement;
      if (parentElement) {
        console.log(
          `🔧 [DEBUG] 尝试在父级元素内查找: ${operation.locator.strategy}=${operation.locator.value}`
        );
        console.log(
          `🔧 [DEBUG] 父级容器信息: ${parentElement.tagName}.${parentElement.className}`
        );

        // 对于容器循环，需要找到正确的表格行容器
        let containerElement = parentElement;
        if (parentElement.tagName === "BUTTON") {
          // 如果父级元素是按钮，需要向上查找到表格行
          containerElement =
            parentElement.closest("tr") ||
            parentElement.closest(".core-table-tr");
          console.log(
            `🔧 [DEBUG] 按钮父级，向上查找表格行容器: ${containerElement
              ? containerElement.tagName + "." + containerElement.className
              : "未找到"
            }`
          );
        }

        // 尝试在容器元素内查找，支持多种选择器策略
        try {
          switch (operation.locator.strategy) {
            case "css":
              clickElement = containerElement
                ? containerElement.querySelector(operation.locator.value)
                : parentElement.querySelector(operation.locator.value);
              break;
            case "id":
              // 对于ID选择器，在父级元素内查找
              clickElement = parentElement.querySelector(
                `#${operation.locator.value}`
              );
              break;
            case "xpath":
              // 对于XPath，需要在父级元素的上下文中执行
              const xpathResult = document.evaluate(
                operation.locator.value,
                parentElement,
                null,
                XPathResult.FIRST_ORDERED_NODE_TYPE,
                null
              );
              clickElement = xpathResult.singleNodeValue;
              break;
            case "text":
              // 在父级元素内查找包含特定文本的元素
              const textElements = parentElement.querySelectorAll("*");
              for (const el of textElements) {
                if (
                  el.textContent &&
                  el.textContent.trim() === operation.locator.value.trim()
                ) {
                  clickElement = el;
                  break;
                }
              }
              break;
            case "contains":
              // 在父级元素内查找包含文本的元素
              const containsElements = parentElement.querySelectorAll("*");
              for (const el of containsElements) {
                if (
                  el.textContent &&
                  el.textContent.includes(operation.locator.value)
                ) {
                  clickElement = el;
                  break;
                }
              }
              break;
          }

          if (clickElement) {
            console.log(
              `🎯 在父级元素内找到目标: ${operation.locator.strategy}=${operation.locator.value}`
            );
          } else {
            console.log(`🔍 在父级元素内未找到，尝试全局查找`);
          }
        } catch (error) {
          console.warn(`🔧 [DEBUG] 父级元素内查找失败:`, error);
        }
      }

      // 如果在父级元素内没找到，或者没有父级元素，则进行全局查找
      if (!clickElement) {
        console.log(
          `🌐 使用全局查找: ${operation.locator.strategy}="${operation.locator.value}"`
        );
        try {
          clickElement = await findElementByStrategy(
            operation.locator.strategy,
            operation.locator.value
          );
        } catch (globalError) {
          console.error(`❌ 全局查找失败:`, globalError);
          throw new Error(
            `找不到点击目标元素: ${operation.locator.strategy}="${operation.locator.value}" (全局查找失败: ${globalError.message})`
          );
        }
      }

      if (!clickElement) {
        throw new Error(
          `找不到点击目标元素: ${operation.locator.strategy}="${operation.locator.value}"`
        );
      }

      // 高亮显示找到的元素
      highlightElement(clickElement, "click");

      // 使用智能滚动函数，在虚拟列表模式下禁用页面滚动
      smartScrollIntoView(clickElement, {
        behavior: "smooth",
        block: "center",
      });
      await new Promise((resolve) => setTimeout(resolve, 300));

      // 在点击前再次检查暂停状态
      if (window.simplifiedExecutionControl) {
        await window.simplifiedExecutionControl.checkPause();
      }

      // 更新状态反馈 - 点击开始
      if (window.updateStatus) {
        const elementInfo =
          clickElement.textContent?.trim() ||
          clickElement.className ||
          clickElement.id ||
          "未知元素";
        window.updateStatus(`👆 点击: ${elementInfo}`, "info");
      }

      // 执行点击
      clickElement.click();
      console.log(`👆 子操作-点击完成: ${operation.locator.value}`);

      // 处理新窗口操作 - 检测多种可能的新窗口标记
      const shouldHandleNewWindow = operation.opensNewWindow ||
        operation.opensNewWindow === "true" ||
        (operation.locator && operation.locator.opensNewWindow) ||
        // 检查点击的元素是否有target="_blank"属性
        (clickElement && (
          clickElement.target === "_blank" ||
          clickElement.getAttribute("target") === "_blank" ||
          (clickElement.tagName === "A" && clickElement.href && !clickElement.href.startsWith("javascript:"))
        ));

      if (shouldHandleNewWindow) {
        console.log("🪟 检测到子操作需要打开新窗口");

        // 🔧 [修复] 新窗口去重检查 - Content Script层面
        const currentTime = Date.now();
        const timeSinceLastWindow = currentTime - window.lastNewWindowTime;

        if (window.isCreatingNewWindow && timeSinceLastWindow < window.newWindowCooldown) {
          console.log(`🚫 [Content Script去重] 新窗口创建冷却中，距离上次创建仅 ${timeSinceLastWindow}ms，跳过重复请求`);
          console.log(`🔄 [Content Script去重] 假设新窗口已经打开，设置窗口上下文标记`);

          // 设置模拟的新窗口上下文，让后续操作知道应该在新窗口中执行
          const mockNewWindowId = Date.now();
          window.currentWindowContextId = mockNewWindowId;
          console.log(`✅ [Content Script去重] 设置模拟新窗口上下文: ${mockNewWindowId}`);

          // 跳过实际的新窗口创建逻辑，直接返回
          return;
        }

        // 🔧 [修复] 设置新窗口创建状态
        window.isCreatingNewWindow = true;
        window.lastNewWindowTime = currentTime;
        console.log(`🔧 [Content Script去重] 设置新窗口创建状态，时间戳: ${currentTime}`);

        // 等待新窗口创建
        const newWindowTimeout = operation.newWindowTimeout || 10000;
        console.log(`⏳ 等待新窗口创建 (${newWindowTimeout}ms)`);

        // 如果需要切换到新窗口
        if (operation.switchToNewWindow !== false) {
          console.log("🔄 需要切换到新窗口，使用简化检测方法");

          try {
            // 等待新窗口创建
            console.log("⏳ 等待新窗口创建...");
            await new Promise((resolve) => setTimeout(resolve, 3000));

            // 简化的新窗口检测：直接设置窗口上下文标记
            // 这样后续操作就知道应该在新窗口中执行
            const mockNewWindowId = Date.now(); // 使用时间戳作为模拟的窗口ID
            window.currentWindowContextId = mockNewWindowId;

            console.log(`✅ 设置新窗口上下文标记: ${mockNewWindowId}`);
            console.log("🔄 后续操作将通过跨窗口机制执行");

            // 🔧 [修复] 新窗口创建完成，重置创建状态
            window.isCreatingNewWindow = false;
            console.log(`🔧 [Content Script去重] 新窗口创建完成，重置创建状态`);

            // 模拟成功响应
            const response = {
              success: true,
              windowId: mockNewWindowId,
              message: "使用简化新窗口检测"
            };

            if (response && response.success) {
              console.log(`✅ 成功切换到新窗口: ${response.windowId}`);
              // 等待新窗口加载完成
              const windowReadyTimeout = operation.windowReadyTimeout || 30000;
              console.log(`⏳ 等待新窗口准备就绪 (${windowReadyTimeout}ms)`);
              await new Promise((resolve) => setTimeout(resolve, windowReadyTimeout));

              // 确保新窗口的content script已准备就绪
              console.log("🔄 检查新窗口content script是否就绪...");
              let contentScriptReady = false;
              for (let attempt = 1; attempt <= 3; attempt++) {
                try {
                  const pingResponse = await chrome.runtime.sendMessage({
                    action: "ping"
                  });
                  if (pingResponse && pingResponse.status === "ready") {
                    contentScriptReady = true;
                    console.log("✅ 新窗口content script已就绪");
                    break;
                  }
                } catch (pingError) {
                  console.log(`🔄 content script就绪检查尝试 ${attempt}/3 失败:`, pingError.message);
                }
                if (attempt < 3) {
                  await new Promise((resolve) => setTimeout(resolve, 500));
                }
              }

              if (!contentScriptReady) {
                console.warn("⚠️ 新窗口content script可能未完全就绪，继续执行...");
              }

              // 设置当前窗口上下文ID，确保后续操作在新窗口中执行
              if (response.windowId) {
                window.currentWindowContextId = response.windowId;
                console.log(`✅ 设置当前窗口上下文ID为: ${window.currentWindowContextId}`);

                // 通知background script更新当前执行窗口
                try {
                  await chrome.runtime.sendMessage({
                    action: "updateCurrentExecutionTab",
                    tabId: response.windowId
                  });
                  console.log(`✅ 通知background script更新执行窗口`);
                } catch (updateError) {
                  console.warn("⚠️ 更新执行窗口ID失败:", updateError.message);
                }
              }
            } else {
              console.warn("⚠️ 切换到新窗口失败:", response?.error || "未知错误");
            }
          } catch (error) {
            console.error("❌ 切换到新窗口时出错:", error);

            // 🔧 [修复] 新窗口创建失败，重置创建状态
            window.isCreatingNewWindow = false;
            console.log(`🔧 [Content Script去重] 新窗口创建失败，重置创建状态`);
          }
        }
      }

      // 更新状态反馈 - 点击完成
      if (window.updateStatus) {
        const elementInfo =
          clickElement.textContent?.trim() ||
          clickElement.className ||
          clickElement.id ||
          "未知元素";
        window.updateStatus(`✅ 点击完成: ${elementInfo}`, "success");
      }

      // 清除高亮
      setTimeout(() => {
        clearElementHighlight(clickElement);
      }, 1000);

      break;

    case "input":
      // 在输入操作前检查暂停状态
      if (window.simplifiedExecutionControl) {
        await window.simplifiedExecutionControl.checkPause();
      }

      let inputElement;
      if (parentElement && operation.locator?.strategy === "css") {
        // 只有CSS选择器才能在父级元素内查找
        inputElement = parentElement.querySelector(operation.locator.value);
        if (!inputElement) {
          console.log(
            `🔍 在父级元素内未找到输入目标，使用全局查找: ${operation.locator.strategy}="${operation.locator.value}"`
          );
          try {
            inputElement = await findElementByStrategy(
              operation.locator.strategy,
              operation.locator.value
            );
          } catch (globalError) {
            console.error(`❌ 全局查找输入元素失败:`, globalError);
            throw new Error(
              `找不到输入目标元素: ${operation.locator.strategy}="${operation.locator.value}" (全局查找失败: ${globalError.message})`
            );
          }
        }
      } else {
        console.log(
          `🌐 使用全局查找输入元素: ${operation.locator.strategy}="${operation.locator.value}"`
        );
        try {
          inputElement = await findElementByStrategy(
            operation.locator.strategy,
            operation.locator.value
          );
        } catch (globalError) {
          console.error(`❌ 全局查找输入元素失败:`, globalError);
          throw new Error(
            `找不到输入目标元素: ${operation.locator.strategy}="${operation.locator.value}" (全局查找失败: ${globalError.message})`
          );
        }
      }
      inputElement.value = operation.text || "";
      inputElement.dispatchEvent(new Event("input", { bubbles: true }));
      inputElement.dispatchEvent(new Event("change", { bubbles: true }));
      console.log(`⌨️ 子操作-输入: "${operation.text}"`);
      break;

    case "wait":
      const duration = operation.duration || 1000;
      console.log(`⏱️ 子操作-等待: ${duration}ms`);

      // 在等待过程中支持暂停检查
      const waitStartTime = Date.now();
      while (Date.now() - waitStartTime < duration) {
        // 每100ms检查一次暂停状态
        if (window.simplifiedExecutionControl) {
          await window.simplifiedExecutionControl.checkPause();
        }
        await new Promise((resolve) =>
          setTimeout(resolve, Math.min(100, duration - (Date.now() - waitStartTime)))
        );
      }
      break;

    case "waitForElement":
      console.log(`🔍 子操作-等待元素: ${operation.locator.value}`);
      const timeout = operation.timeout || 30000;
      const startTime = Date.now();
      while (Date.now() - startTime < timeout) {
        // 在等待元素过程中检查暂停状态
        if (window.simplifiedExecutionControl) {
          await window.simplifiedExecutionControl.checkPause();
        }

        try {
          const waitElement = await findElementByStrategy(
            operation.locator.strategy,
            operation.locator.value,
            100
          );
          if (waitElement) {
            console.log(`✅ 元素已出现: ${operation.locator.value}`);
            break;
          }
        } catch (error) {
          // 继续等待
        }
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
      break;

    case "check":
      let checkElement;
      if (parentElement && operation.locator?.strategy === "css") {
        checkElement = parentElement.querySelector(operation.locator.value);
        if (!checkElement) {
          checkElement = await findElementByStrategy(
            operation.locator.strategy,
            operation.locator.value
          );
        }
      } else {
        checkElement = await findElementByStrategy(
          operation.locator.strategy,
          operation.locator.value
        );
      }
      if (!checkElement.checked) {
        checkElement.checked = true;
        checkElement.dispatchEvent(new Event("change", { bubbles: true }));
        console.log(`☑️ 子操作-勾选复选框`);
      }
      break;

    case "select":
      let selectElement;
      if (parentElement && operation.locator?.strategy === "css") {
        selectElement = parentElement.querySelector(operation.locator.value);
        if (!selectElement) {
          selectElement = await findElementByStrategy(
            operation.locator.strategy,
            operation.locator.value
          );
        }
      } else {
        selectElement = await findElementByStrategy(
          operation.locator.strategy,
          operation.locator.value
        );
      }
      selectElement.value = operation.value || "";
      selectElement.dispatchEvent(new Event("change", { bubbles: true }));
      console.log(`📋 子操作-选择选项: ${operation.value}`);
      break;

    case "autoLoop":
      console.log(`🔁 子操作-自循环开始: ${operation.locator.value}`);
      await executeSubOperationAutoLoop(operation, parentElement);
      break;

    case "loop":
      console.log(`🔁 子操作-循环开始: ${operation.locator.value}`);
      if (
        operation.loopType === "self" ||
        operation.loopType === "simpleLoop"
      ) {
        // 自循环，等同于autoLoop
        await executeSubOperationAutoLoop(operation, parentElement);
      } else {
        // 其他循环类型，递归调用executeLoopStep
        await executeLoopStep(operation);
      }
      break;

    case "drag":
      console.log(`🖱️ 子操作-拖拽开始: ${operation.locator.value}`);
      let dragElement;
      if (parentElement && operation.locator?.strategy === "css") {
        // 首先尝试在父级元素内查找
        console.log(`🔍 在父级容器内查找拖拽元素: ${operation.locator.value}`);
        console.log(
          `🔍 父级容器信息: ${parentElement.tagName}.${parentElement.className}`
        );

        // 对于容器循环，需要找到正确的表格行容器
        let containerElement = parentElement;
        if (parentElement.tagName === "BUTTON") {
          // 如果父级元素是按钮，需要向上查找到表格行
          containerElement =
            parentElement.closest("tr") ||
            parentElement.closest(".core-table-tr");
          console.log(
            `🔍 按钮父级，向上查找表格行容器: ${containerElement
              ? containerElement.tagName + "." + containerElement.className
              : "未找到"
            }`
          );
        }

        if (containerElement) {
          dragElement = containerElement.querySelector(operation.locator.value);
          if (dragElement) {
            console.log(
              `🔍 在容器内找到拖拽目标: ${dragElement.id || dragElement.className
              }`
            );
          } else {
            console.log(`🔍 在容器内未找到拖拽目标，使用全局查找`);
            dragElement = await findElementByStrategy(
              operation.locator.strategy,
              operation.locator.value
            );
          }
        } else {
          console.log(`🔍 未找到有效容器，使用全局查找`);
          dragElement = await findElementByStrategy(
            operation.locator.strategy,
            operation.locator.value
          );
        }
      } else {
        dragElement = await findElementByStrategy(
          operation.locator.strategy,
          operation.locator.value
        );
      }

      if (!dragElement) {
        throw new Error(`未找到拖拽目标元素: ${operation.locator.value}`);
      }

      // 执行拖拽操作
      const rect = dragElement.getBoundingClientRect();
      const startX = rect.left + rect.width / 2;
      const startY = rect.top + rect.height / 2;
      const endX = startX + (operation.horizontalDistance || 0);
      const endY = startY + (operation.verticalDistance || 0);

      console.log(
        `🖱️ 拖拽详情: 从(${startX}, ${startY}) 到 (${endX}, ${endY}), 距离: ${operation.horizontalDistance || 0
        }px, ${operation.verticalDistance || 0}px`
      );

      // 更新状态反馈 - 拖拽开始
      if (window.updateStatus) {
        window.updateStatus(
          `🖱️ 开始拖拽: ${dragElement.id || "拖拽元素"} (${operation.horizontalDistance || 0
          }px, ${operation.verticalDistance || 0}px)`,
          "info"
        );
      }

      // 添加拖拽前的视觉高亮
      const originalStyle = dragElement.style.cssText;
      dragElement.style.border = "3px solid #ff6b6b";
      dragElement.style.boxShadow = "0 0 10px rgba(255, 107, 107, 0.5)";

      // 检查是否是HTML5拖拽元素
      if (dragElement.draggable) {
        console.log("🖱️ 检测到HTML5拖拽元素，使用增强拖拽方法");
        await performEnhancedDragOperation(
          dragElement,
          startX,
          startY,
          endX,
          endY,
          {
            dragSpeed: operation.dragSpeed || 100,
            waitAfterDrag: operation.waitAfterDrag || 1000,
          }
        );
      } else {
        console.log("🖱️ 使用标准鼠标事件拖拽");
        await performDragOperation(dragElement, startX, startY, endX, endY, {
          dragSpeed: operation.dragSpeed || 100,
          waitAfterDrag: operation.waitAfterDrag || 1000,
        });
      }

      // 恢复原始样式
      dragElement.style.cssText = originalStyle;

      // 更新状态反馈 - 拖拽完成
      if (window.updateStatus) {
        window.updateStatus(
          `✅ 拖拽完成: ${dragElement.id || "拖拽元素"}`,
          "success"
        );
      }

      console.log(`✅ 子操作-拖拽完成`);
      break;

    case "closeWindow":
      console.log(`🗑️ 子操作-关闭窗口: ${operation.closeTarget || "current"}`);

      // 通知background脚本处理关闭窗口
      if (typeof chrome !== 'undefined' && chrome.runtime) {
        try {
          const response = await chrome.runtime.sendMessage({
            action: 'handleCloseWindow',
            config: {
              closeTarget: operation.closeTarget || "current",
              targetWindowId: operation.targetWindowId,
              returnToPrevious: operation.returnToPrevious !== false,
              waitAfterClose: operation.waitAfterClose || 1000
            }
          });

          if (response && response.success) {
            console.log(`✅ 子操作-关闭窗口完成: ${response.message}`);
          } else {
            throw new Error(response?.error || "关闭窗口失败");
          }
        } catch (error) {
          console.error(`❌ 关闭窗口失败:`, error);
          throw new Error(`关闭窗口失败: ${error.message}`);
        }
      } else {
        // 如果没有chrome API，尝试关闭当前窗口
        if ((operation.closeTarget || "current") === "current") {
          window.close();
          console.log(`✅ 子操作-关闭窗口命令已发送`);
        } else {
          throw new Error("无chrome API支持，无法关闭指定窗口");
        }
      }
      break;

    default:
      throw new Error(`不支持的子操作类型: ${operation.type}`);
  }
}

// 执行子操作中的自循环
async function executeSubOperationAutoLoop(operation, parentElement = null) {
  // 在执行自循环前检查暂停状态
  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  console.log(`🔁 开始执行子操作自循环: ${operation.locator.value}`);

  // 查找所有匹配的元素
  let elements;
  if (parentElement && operation.locator?.strategy === "css") {
    // 只有CSS选择器才能在父级元素内查找
    elements = Array.from(
      parentElement.querySelectorAll(operation.locator.value)
    );
    if (elements.length === 0) {
      // 如果在父级元素内找不到，尝试全局查找
      elements = await findElementsByStrategy(
        operation.locator.strategy,
        operation.locator.value
      );
      console.log(`🔍 在父级元素内未找到，使用全局查找`);
    } else {
      console.log(`🔍 在父级元素内找到 ${elements.length} 个目标`);
    }
  } else {
    // 对于非CSS选择器或没有父级元素的情况，直接全局查找
    elements = await findElementsByStrategy(
      operation.locator.strategy,
      operation.locator.value
    );
  }

  if (elements.length === 0) {
    throw new Error(`自循环未找到匹配元素: ${selector}`);
  }

  // 计算处理范围
  const startIndex = operation.startIndex || 0;
  const endIndex =
    operation.endIndex === -1
      ? elements.length - 1
      : operation.endIndex || elements.length - 1;
  const actualEndIndex = Math.min(endIndex, elements.length - 1);

  console.log(
    `📊 自循环找到 ${elements.length} 个元素，处理范围: ${startIndex} - ${actualEndIndex}`
  );

  // 获取操作类型和配置
  const actionType = operation.actionType || operation.operationType || "click";
  const actionDelay = operation.actionDelay || operation.operationDelay || 200;
  const errorHandling = operation.errorHandling || "continue";

  // 依次处理每个元素
  let successCount = 0;
  let errorCount = 0;

  for (let i = startIndex; i <= actualEndIndex; i++) {
    // 在每次循环迭代前检查暂停状态
    if (window.simplifiedExecutionControl) {
      await window.simplifiedExecutionControl.checkPause();
    }

    console.log(`🎯 自循环处理第 ${i + 1}/${actualEndIndex + 1} 个元素`);

    try {
      const element = elements[i];

      // 添加绿色执行进度高亮
      highlightExecutionProgress(element);

      await executeAutoLoopAction(element, operation, actionType);
      successCount++;

      console.log(`✅ 第 ${i + 1} 个元素${actionType}操作完成`);

      // 操作间隔
      if (actionDelay > 0 && i < actualEndIndex) {
        await new Promise((resolve) => setTimeout(resolve, actionDelay));
      }

      // 清除执行进度高亮
      clearExecutionProgress(element);
    } catch (error) {
      errorCount++;

      const element = elements[i];
      console.error(`❌ 第 ${i + 1} 个元素操作失败:`, error);

      // 清除执行进度高亮（即使失败也要清除）
      clearExecutionProgress(element);

      if (errorHandling === "stop") {
        throw new Error(`自循环在第 ${i + 1} 个元素处停止: ${error.message}`);
      }
      // 继续处理下一个元素
    }
  }

  console.log(
    `🎉 自循环执行完成: 成功 ${successCount} 个，失败 ${errorCount} 个`
  );
}

// 执行自循环中的单个元素操作
async function executeAutoLoopAction(element, operation, actionType) {
  switch (actionType) {
    case "click":
      element.click();
      break;

    case "input":
      const inputText = operation.inputText || "";
      element.value = inputText;
      element.dispatchEvent(new Event("input", { bubbles: true }));
      element.dispatchEvent(new Event("change", { bubbles: true }));
      break;

    case "check":
      if (element.type === "checkbox" && !element.checked) {
        element.checked = true;
        element.dispatchEvent(new Event("change", { bubbles: true }));
        console.log(`☑️ 勾选复选框: ${element.id || element.name || "未命名"}`);
      } else if (element.type === "checkbox") {
        console.log(
          `ℹ️ 复选框已勾选: ${element.id || element.name || "未命名"}`
        );
      } else {
        throw new Error("check操作只能用于checkbox元素");
      }
      break;

    case "uncheck":
      if (element.type === "checkbox" && element.checked) {
        element.checked = false;
        element.dispatchEvent(new Event("change", { bubbles: true }));
        console.log(
          `☐ 取消勾选复选框: ${element.id || element.name || "未命名"}`
        );
      } else if (element.type === "checkbox") {
        console.log(
          `ℹ️ 复选框已取消勾选: ${element.id || element.name || "未命名"}`
        );
      } else {
        throw new Error("uncheck操作只能用于checkbox元素");
      }
      break;

    case "hover":
      element.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
      break;

    case "focus":
      element.focus();
      break;

    default:
      throw new Error(`不支持的自循环操作类型: ${actionType}`);
  }
}

// 测试条件判断
function testCondition(condition) {
  console.log("🧪 测试条件:", condition);

  try {
    // 清除之前的测试高亮
    clearTestHighlights();

    // 首先获取元素
    const locator = condition.locator;
    if (!locator || !locator.strategy || !locator.value) {
      return {
        success: false,
        error: "缺少定位器配置",
      };
    }

    // 查找元素
    const element = findSingleElement(locator.strategy, locator.value);
    if (!element) {
      return {
        success: false,
        error: "元素未找到",
        conditionMet: false,
      };
    }

    // 高亮元素
    highlightTestElements([element]);

    // 执行条件判断
    let conditionResult = false;
    let actualValue = "";
    let expectedValue = condition.expectedValue || "";
    const attributeName = condition.attributeName || "";

    // 获取实际值
    switch (condition.conditionType) {
      case "attribute":
        actualValue = element.getAttribute(attributeName) || "";
        break;
      case "text":
        actualValue = element.textContent || "";
        break;
      case "class":
        actualValue = element.className || "";
        break;
      case "style":
        actualValue = getComputedStyle(element)[attributeName] || "";
        break;
      case "value":
        actualValue = element.value || "";
        break;
      case "exists":
        conditionResult = true; // 元素已找到
        break;
      case "visible":
        conditionResult = element.offsetParent !== null;
        break;
    }

    // 执行比较
    if (
      condition.conditionType !== "exists" &&
      condition.conditionType !== "visible"
    ) {
      switch (condition.comparisonType) {
        case "equals":
          conditionResult = actualValue === expectedValue;
          break;
        case "notEquals":
          conditionResult = actualValue !== expectedValue;
          break;
        case "contains":
          conditionResult = actualValue.includes(expectedValue);
          break;
        case "notContains":
          conditionResult = !actualValue.includes(expectedValue);
          break;
        case "startsWith":
          conditionResult = actualValue.startsWith(expectedValue);
          break;
        case "endsWith":
          conditionResult = actualValue.endsWith(expectedValue);
          break;
        case "isEmpty":
          conditionResult = actualValue === "";
          break;
        case "isNotEmpty":
          conditionResult = actualValue !== "";
          break;
        case "hasAttribute":
          conditionResult = element.hasAttribute(attributeName);
          break;
        case "notHasAttribute":
          conditionResult = !element.hasAttribute(attributeName);
          break;
      }
    }

    // 返回结果
    return {
      success: true,
      conditionMet: conditionResult,
      message: `条件${conditionResult ? "满足" : "不满足"}`,
      actualValue,
      expectedValue,
    };
  } catch (error) {
    console.error("❌ 测试条件失败:", error);
    return {
      success: false,
      error: error.message,
    };
  }
}

// 查找单个元素
function findSingleElement(strategy, value) {
  try {
    switch (strategy) {
      case "css":
        return document.querySelector(value);
      case "xpath":
        const xpathResult = document.evaluate(
          value,
          document,
          null,
          XPathResult.FIRST_ORDERED_NODE_TYPE,
          null
        );
        return xpathResult.singleNodeValue;
      case "id":
        return document.getElementById(value);
      case "className":
        const elements = document.getElementsByClassName(value);
        return elements.length > 0 ? elements[0] : null;
      case "text":
        return Array.from(document.querySelectorAll("*")).find(
          (el) => el.textContent && el.textContent.trim() === value.trim()
        );
      case "contains":
        return Array.from(document.querySelectorAll("*")).find(
          (el) => el.textContent && el.textContent.includes(value)
        );
      case "tagName":
        const tagElements = document.getElementsByTagName(value);
        return tagElements.length > 0 ? tagElements[0] : null;
      default:
        throw new Error(`不支持的定位策略: ${strategy}`);
    }
  } catch (error) {
    console.error(`查找元素失败 (${strategy}: ${value}):`, error);
    return null;
  }
}

// 测试定位器元素数量
function testLocatorElements(locator) {
  console.log("🔍 测试定位器:", locator);

  try {
    // 清除之前的测试高亮
    clearTestHighlights();

    let elements;

    switch (locator.strategy) {
      case "css":
        elements = document.querySelectorAll(locator.value);
        break;
      case "xpath":
        const xpathResult = document.evaluate(
          locator.value,
          document,
          null,
          XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
          null
        );
        elements = [];
        for (let i = 0; i < xpathResult.snapshotLength; i++) {
          elements.push(xpathResult.snapshotItem(i));
        }
        break;
      case "id":
        const idElement = document.getElementById(locator.value);
        elements = idElement ? [idElement] : [];
        break;
      case "className":
        elements = document.getElementsByClassName(locator.value);
        break;
      case "tagName":
        elements = document.getElementsByTagName(locator.value);
        break;
      case "text":
        // 精确文本匹配，使用遍历方式避免XPath转义问题
        elements = Array.from(document.querySelectorAll("*")).filter(
          (el) =>
            el.textContent && el.textContent.trim() === locator.value.trim()
        );
        break;
      case "contains":
        // 包含文本匹配，使用遍历方式避免XPath转义问题
        elements = Array.from(document.querySelectorAll("*")).filter(
          (el) => el.textContent && el.textContent.includes(locator.value)
        );
        break;
      default:
        throw new Error(`不支持的定位策略: ${locator.strategy}`);
    }

    const count = elements.length;
    console.log(`✅ 找到 ${count} 个匹配元素`);

    // 如果找到元素，添加测试高亮效果
    if (count > 0) {
      highlightTestElements(Array.from(elements));
    }

    return { count };
  } catch (error) {
    console.error("❌ 测试定位器失败:", error);
    // 发生错误时也清除高亮
    clearTestHighlights();
    throw error;
  }
}

// 高亮元素
function highlightElement(element, type = "processing") {
  if (!element) return;

  // 保存原始样式
  if (!element._originalStyle) {
    element._originalStyle = {
      outline: element.style.outline || "",
      backgroundColor: element.style.backgroundColor || "",
      transition: element.style.transition || "",
    };
  }

  // 设置高亮样式
  element.style.transition = "all 0.3s ease";

  switch (type) {
    case "processing":
      element.style.outline = "3px solid #3498db";
      element.style.backgroundColor = "rgba(52, 152, 219, 0.1)";
      break;
    case "click":
      element.style.outline = "3px solid #f39c12";
      element.style.backgroundColor = "rgba(243, 156, 18, 0.2)";
      break;
    case "input":
      element.style.outline = "3px solid #9b59b6";
      element.style.backgroundColor = "rgba(155, 89, 182, 0.1)";
      break;
    case "loop":
      element.style.outline = "3px solid #e67e22";
      element.style.backgroundColor = "rgba(230, 126, 34, 0.15)";
      break;
    case "success":
      element.style.outline = "3px solid #27ae60";
      element.style.backgroundColor = "rgba(39, 174, 96, 0.1)";
      break;
    case "error":
      element.style.outline = "3px solid #e74c3c";
      element.style.backgroundColor = "rgba(231, 76, 60, 0.1)";
      break;
  }

  // 使用智能滚动函数，在虚拟列表模式下禁用页面滚动
  smartScrollIntoView(element, { behavior: "smooth", block: "center" });
}

// 清除元素高亮
function clearElementHighlight(element) {
  if (!element || !element._originalStyle) return;

  // 恢复原始样式
  element.style.outline = element._originalStyle.outline;
  element.style.backgroundColor = element._originalStyle.backgroundColor;
  element.style.transition = element._originalStyle.transition;

  // 清除保存的样式
  delete element._originalStyle;
}

// 全局变量存储测试高亮的元素
let testHighlightedElements = [];

// 高亮测试找到的元素
function highlightTestElements(elements) {
  console.log(`🎯 开始高亮 ${elements.length} 个测试元素`);

  // 清除之前的测试高亮
  clearTestHighlights();

  elements.forEach((element, index) => {
    if (!element) return;

    // 保存原始样式
    if (!element._testOriginalStyle) {
      element._testOriginalStyle = {
        outline: element.style.outline || "",
        backgroundColor: element.style.backgroundColor || "",
        transition: element.style.transition || "",
        zIndex: element.style.zIndex || "",
      };
    }

    // 设置测试高亮样式（橙色）
    element.style.transition = "all 0.3s ease";
    element.style.outline = "2px solid orange";
    element.style.backgroundColor = "rgba(255, 165, 0, 0.1)";
    element.style.zIndex = "9999";

    // 标记为测试高亮元素
    element._isTestHighlighted = true;
    testHighlightedElements.push(element);

    console.log(`✅ 已高亮第 ${index + 1} 个元素`);
  });

  // 滚动到第一个元素
  if (elements.length > 0 && elements[0]) {
    smartScrollIntoView(elements[0], {
      behavior: "smooth",
      block: "center",
      inline: "center",
    });
    console.log("📍 已滚动到第一个匹配元素");
  }
}

// 清除所有测试高亮
function clearTestHighlights() {
  console.log(`🧹 清除 ${testHighlightedElements.length} 个测试高亮元素`);

  testHighlightedElements.forEach((element) => {
    if (element && element._testOriginalStyle) {
      // 恢复原始样式
      element.style.outline = element._testOriginalStyle.outline;
      element.style.backgroundColor =
        element._testOriginalStyle.backgroundColor;
      element.style.transition = element._testOriginalStyle.transition;
      element.style.zIndex = element._testOriginalStyle.zIndex;

      // 清除标记和保存的样式
      delete element._testOriginalStyle;
      delete element._isTestHighlighted;
    }
  });

  // 清空数组
  testHighlightedElements = [];
  console.log("✅ 所有测试高亮已清除");
}

// 高亮执行进度（绿色）
function highlightExecutionProgress(element) {
  if (!element) return;

  console.log("🟢 添加执行进度高亮");

  // 保存原始样式（如果还没保存的话）
  if (!element._executionOriginalStyle) {
    element._executionOriginalStyle = {
      outline: element.style.outline || "",
      backgroundColor: element.style.backgroundColor || "",
      transition: element.style.transition || "",
      zIndex: element.style.zIndex || "",
    };
  }

  // 设置执行进度高亮样式（绿色）
  element.style.transition = "all 0.3s ease";
  element.style.outline = "3px solid #27ae60";
  element.style.backgroundColor = "rgba(39, 174, 96, 0.1)";
  element.style.zIndex = "10000"; // 比测试高亮更高的层级

  // 标记为执行进度高亮
  element._isExecutionHighlighted = true;

  // 滚动到当前元素
  smartScrollIntoView(element, {
    behavior: "smooth",
    block: "center",
    inline: "center",
  });
}

// 清除执行进度高亮
function clearExecutionProgress(element) {
  if (!element || !element._executionOriginalStyle) return;

  console.log("🧹 清除执行进度高亮");

  // 恢复原始样式
  element.style.outline = element._executionOriginalStyle.outline;
  element.style.backgroundColor =
    element._executionOriginalStyle.backgroundColor;
  element.style.transition = element._executionOriginalStyle.transition;
  element.style.zIndex = element._executionOriginalStyle.zIndex;

  // 清除标记和保存的样式
  delete element._executionOriginalStyle;
  delete element._isExecutionHighlighted;
}

/**
 * 执行虚拟列表循环
 * 智能遍历虚拟列表，自动滚动并点击所有未处理的项目
 */
async function executeVirtualListLoop(step) {
  const loopName = step.name || `虚拟列表循环`;
  console.log(`📜 开始执行虚拟列表循环: ${loopName}`);

  // 敏感词检测模块已内联，无需加载

  // 设置虚拟列表模式标志，禁用页面滚动
  window.isVirtualListMode = true;
  console.log(`🚫 已启用虚拟列表模式，禁用页面滚动`);

  // 设置虚拟列表模式标志，禁用页面滚动
  window.isVirtualListMode = true;
  console.log(`🚫 已启用虚拟列表模式，禁用页面滚动`);

  // 验证配置
  if (!step.virtualListContainer || !step.virtualListContainer.value) {
    throw new Error("虚拟列表容器定位配置缺失");
  }
  if (!step.virtualListTitleLocator || !step.virtualListTitleLocator.value) {
    throw new Error("虚拟列表标题定位配置缺失");
  }

  // 获取容器元素
  const containerElements = await findElementsByStrategy(
    step.virtualListContainer.strategy,
    step.virtualListContainer.value
  );
  if (containerElements.length === 0) {
    throw new Error(`未找到虚拟列表容器: ${step.virtualListContainer.value}`);
  }
  const container = containerElements[0];
  console.log(`📦 找到虚拟列表容器`);

  // 初始化状态
  const processedTitles = new Set();
  const scrollDistance = step.virtualListScrollDistance || 100;
  const waitTime = step.virtualListWaitTime || 1000;
  const maxRetries = step.virtualListMaxRetries || 10;
  let retryCount = 0;
  let noNewItemsCount = 0;
  let totalProcessed = 0;

  console.log(
    `⚙️ 配置: 滚动距离=${scrollDistance}px, 等待时间=${waitTime}ms, 最大重试=${maxRetries}`
  );

  while (retryCount < maxRetries && noNewItemsCount < 5) {
    // 检查暂停状态
    if (window.simplifiedExecutionControl) {
      await window.simplifiedExecutionControl.checkPause();
    }

    try {
      // 收集当前可见的标题
      const visibleTitles = await collectVisibleTitles(
        step.virtualListTitleLocator
      );
      console.log(`👀 当前可见 ${visibleTitles.length} 个标题`);

      // 逐一检查每个可见标题，找到第一个未处理的
      let unprocessedTitle = null;
      for (const title of visibleTitles) {
        if (!processedTitles.has(title.text)) {
          unprocessedTitle = title;
          console.log(`🔍 找到未处理标题: "${title.text}"`);
          break;
        } else {
          console.log(`⏭️ 跳过已处理标题: "${title.text}"`);
        }
      }

      if (unprocessedTitle) {
        console.log(`🎯 处理标题: "${unprocessedTitle.text}"`);

        // 敏感词检测
        let shouldSkip = false;
        if (
          step.sensitiveWordDetection &&
          step.sensitiveWordDetection.enabled
        ) {
          console.log(
            `🔍 虚拟列表敏感词检测 - 标题: "${unprocessedTitle.text}"`
          );

          try {
            // 创建敏感词检测器实例
            const detector = new window.SensitiveWordDetector();

            // 使用新的检测方法，支持父级容器定位
            const skipResult = await detector.checkShouldSkipElement(
              unprocessedTitle.element,
              step.sensitiveWordDetection
            );

            if (skipResult.shouldSkip) {
              shouldSkip = true;
              const skipMessage = `🚫 ${unprocessedTitle.text} 检测到敏感词：${skipResult.matchedWords.join(", ")}，跳过执行`;
              console.log(skipMessage);

              // 添加到日志显示
              if (window.simplifiedExecutionControl) {
                window.simplifiedExecutionControl.addLog(skipMessage, 'warning');
              }

              // 高亮显示被跳过的元素
              if (unprocessedTitle.element) {
                unprocessedTitle.element.style.border = "2px solid orange";
                unprocessedTitle.element.style.backgroundColor =
                  "rgba(255, 165, 0, 0.2)";
                setTimeout(() => {
                  if (unprocessedTitle.element.style) {
                    unprocessedTitle.element.style.border = "";
                    unprocessedTitle.element.style.backgroundColor = "";
                  }
                }, 2000);
              }

              // 标记为已处理（跳过）
              processedTitles.add(unprocessedTitle.text);
              noNewItemsCount = 0;

              // 跳过敏感词后也要滚动，继续处理下一个
              console.log(`📜 跳过敏感词后滚动容器 ${scrollDistance}px`);
              container.scrollTop += scrollDistance;
              await new Promise((resolve) => setTimeout(resolve, waitTime));
            } else {
              console.log(
                `✅ 虚拟列表标题通过敏感词检测: "${unprocessedTitle.text}"`
              );
            }
          } catch (error) {
            console.error(`❌ 虚拟列表敏感词检测失败: ${error.message}`);
            // 检测失败时继续执行，避免影响正常流程
          }
        }

        if (!shouldSkip) {
          try {
            // 🔧 [修复] 在点击前再次检查停止状态
            if (window.simplifiedExecutionControl) {
              await window.simplifiedExecutionControl.checkPause();
            }

            // 🔧 [修复] 在处理前再次检查是否已被处理（防止并发重复处理）
            if (processedTitles.has(unprocessedTitle.text)) {
              console.log(`⏭️ [去重检查] 标题 "${unprocessedTitle.text}" 已被处理，跳过`);
              continue;
            }

            // 🔧 [修复] 立即标记为正在处理，防止并发重复
            processedTitles.add(unprocessedTitle.text);
            console.log(`🔒 [去重保护] 立即标记 "${unprocessedTitle.text}" 为已处理，防止重复`);

            // 点击对应的按钮（使用循环操作的定位器）
            await clickVirtualListItem(unprocessedTitle, step);

            // 🔧 [修复] 在点击后立即检查停止状态
            if (window.simplifiedExecutionControl) {
              await window.simplifiedExecutionControl.checkPause();
            }

            // 标记为已处理
            processedTitles.add(unprocessedTitle.text);
            totalProcessed++;
            noNewItemsCount = 0;

            console.log(
              `✅ 已处理: "${unprocessedTitle.text}" (总计: ${totalProcessed})`
            );

            // 发送步骤更新到浮层
            const stepMessage = {
              type: 'FROM_CONTENT_SCRIPT',
              action: 'executionStatusUpdate',
              data: {
                isRunning: true,
                isPaused: false,
                message: `正在处理: ${unprocessedTitle.text}`,
                currentStep: totalProcessed,
                totalSteps: `Max` // 虚拟列表无法预知总数
              },
              timestamp: Date.now()
            };
            window.postMessage(stepMessage, '*');
            console.log('📤 发送步骤更新到浮层:', stepMessage.data);

            // 操作后等待
            if (step.operationDelay) {
              console.log(`⏳ 操作延迟 ${step.operationDelay}ms`);
              await new Promise((resolve) =>
                setTimeout(resolve, step.operationDelay)
              );

              // 等待后再次检查暂停状态
              if (window.simplifiedExecutionControl) {
                await window.simplifiedExecutionControl.checkPause();
              }
            }

            // 处理完一个项目后立即滚动
            const beforeScroll = container.scrollTop;
            console.log(
              `📜 处理完项目后滚动容器 ${scrollDistance}px (当前位置: ${beforeScroll})`
            );
            container.scrollTop += scrollDistance;
            const afterScroll = container.scrollTop;
            console.log(`📜 滚动完成，位置: ${beforeScroll} → ${afterScroll}`);

            // 等待新内容渲染
            console.log(`⏳ 等待新内容渲染 ${waitTime}ms`);
            await new Promise((resolve) => setTimeout(resolve, waitTime));

            // 等待后检查暂停状态
            if (window.simplifiedExecutionControl) {
              await window.simplifiedExecutionControl.checkPause();
            }
          } catch (clickError) {
            // 如果是停止信号，直接重新抛出，停止整个循环
            if (clickError.isStopSignal || clickError.message === 'EXECUTION_STOPPED') {
              console.log(`🛑 虚拟列表循环收到停止信号，停止执行`);
              throw clickError;
            }

            console.log(
              `❌ 点击失败: "${unprocessedTitle.text}" - ${clickError.message}`
            );

            // 标记红色边框
            try {
              unprocessedTitle.element.style.border = "2px solid red";
              setTimeout(() => {
                if (unprocessedTitle.element.style) {
                  unprocessedTitle.element.style.border = "";
                }
              }, 3000);
            } catch (e) {
              // 忽略样式设置错误
            }

            // 仍然标记为已处理，避免重复尝试
            processedTitles.add(unprocessedTitle.text);

            // 即使失败也要滚动，继续处理下一个
            console.log(`📜 点击失败后滚动容器 ${scrollDistance}px`);
            container.scrollTop += scrollDistance;
            await new Promise((resolve) => setTimeout(resolve, waitTime));
          }
        }
      } else {
        noNewItemsCount++;
        console.log(`ℹ️ 当前可见项目都已处理 (连续 ${noNewItemsCount}/5 次)`);

        // 即使没有新项目也要滚动，尝试加载更多内容
        console.log(
          `📜 尝试滚动加载更多内容 ${scrollDistance}px (总已处理: ${totalProcessed})`
        );
        container.scrollTop += scrollDistance;

        // 等待新内容渲染
        await new Promise((resolve) => setTimeout(resolve, waitTime));
      }

      // retryCount 不在这里增加，只在出错时增加
    } catch (error) {
      console.log(`❌ 虚拟列表处理出错: ${error.message}`);

      // 🔧 [修复] 如果是停止信号，直接重新抛出，不进行重试
      if (error.isStopSignal || error.message === 'EXECUTION_STOPPED') {
        console.log(`🛑 虚拟列表循环检测到停止信号，立即停止，不进行重试`);
        throw error;
      }

      retryCount++;

      if (retryCount >= maxRetries) {
        throw new Error(
          `虚拟列表处理失败，已达到最大重试次数: ${error.message}`
        );
      }

      // 短暂等待后重试
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }

  console.log(`🎉 虚拟列表循环完成，共处理 ${totalProcessed} 个项目`);

  // 清除虚拟列表模式标志，恢复正常滚动
  window.isVirtualListMode = false;
  console.log(`✅ 已退出虚拟列表模式，恢复正常滚动`);
}

/**
 * 收集当前可见的标题元素
 */
async function collectVisibleTitles(titleLocator) {
  const titleElements = await findElementsByStrategy(
    titleLocator.strategy,
    titleLocator.value
  );
  const visibleTitles = [];

  for (const element of titleElements) {
    // 检查元素是否在视口中可见（放宽条件，只要部分可见即可）
    const rect = element.getBoundingClientRect();
    const isVisible =
      rect.bottom > 0 &&
      rect.top < window.innerHeight &&
      rect.right > 0 &&
      rect.left < window.innerWidth;

    if (isVisible && element.innerText && element.innerText.trim()) {
      visibleTitles.push({
        text: element.innerText.trim(),
        element: element,
      });
    }
  }

  return visibleTitles;
}

/**
 * 点击虚拟列表项对应的按钮
 */
async function clickVirtualListItem(titleInfo, step) {
  // 从标题元素开始，查找对应的可点击按钮
  // 使用循环操作的定位器来找到按钮
  const buttonElements = await findElementsByStrategy(
    step.locator.strategy,
    step.locator.value
  );

  console.log(
    `🔍 找到 ${buttonElements.length} 个可点击按钮，正在匹配标题: "${titleInfo.text}"`
  );

  // 尝试找到与当前标题相关的按钮
  // 策略1：查找同一个父容器内的按钮
  let targetButton = null;

  // 首先尝试在标题元素的父容器中查找按钮
  let currentElement = titleInfo.element;
  for (let level = 0; level < 5; level++) {
    // 最多向上查找5层
    if (!currentElement || !currentElement.parentElement) break;
    currentElement = currentElement.parentElement;

    // 在当前容器内查找按钮
    for (const button of buttonElements) {
      if (currentElement.contains(button)) {
        targetButton = button;
        console.log(`✅ 在第${level + 1}层父容器中找到匹配按钮`);
        break;
      }
    }
    if (targetButton) break;
  }

  // 策略2：如果没找到，使用距离匹配
  if (!targetButton) {
    console.log(`🔍 使用距离匹配策略查找按钮`);
    let minDistance = Infinity;

    const titleRect = titleInfo.element.getBoundingClientRect();
    const titleCenterX = titleRect.left + titleRect.width / 2;
    const titleCenterY = titleRect.top + titleRect.height / 2;

    for (const button of buttonElements) {
      const buttonRect = button.getBoundingClientRect();

      // 只考虑可见的按钮
      if (buttonRect.width === 0 || buttonRect.height === 0) continue;

      const buttonCenterX = buttonRect.left + buttonRect.width / 2;
      const buttonCenterY = buttonRect.top + buttonRect.height / 2;

      // 计算距离
      const distance = Math.sqrt(
        Math.pow(titleCenterX - buttonCenterX, 2) +
        Math.pow(titleCenterY - buttonCenterY, 2)
      );

      if (distance < minDistance) {
        minDistance = distance;
        targetButton = button;
      }
    }

    if (targetButton) {
      console.log(
        `✅ 通过距离匹配找到按钮，距离: ${Math.round(minDistance)}px`
      );
    }
  }

  if (!targetButton) {
    throw new Error(`未找到与标题 "${titleInfo.text}" 对应的按钮`);
  }

  // 确保按钮在虚拟列表容器内可见，但不滚动整个页面
  console.log(`📍 确保按钮在虚拟列表容器内可见`);

  // 获取虚拟列表容器
  const containerElements = await findElementsByStrategy(
    step.virtualListContainer.strategy,
    step.virtualListContainer.value
  );

  if (containerElements.length > 0) {
    const listContainer = containerElements[0];
    const buttonRect = targetButton.getBoundingClientRect();
    const containerRect = listContainer.getBoundingClientRect();

    // 检查按钮是否在容器可视区域内
    const isButtonVisible =
      buttonRect.top >= containerRect.top &&
      buttonRect.bottom <= containerRect.bottom &&
      buttonRect.left >= containerRect.left &&
      buttonRect.right <= containerRect.right;

    if (!isButtonVisible) {
      console.log(`📜 按钮不在容器可视区域内，调整容器滚动位置`);

      // 计算需要滚动的距离
      const scrollOffset =
        buttonRect.top - containerRect.top - containerRect.height / 2;
      listContainer.scrollTop += scrollOffset;

      console.log(`📜 容器滚动调整: ${scrollOffset}px`);
    } else {
      console.log(`✅ 按钮已在容器可视区域内`);
    }
  }

  await new Promise((resolve) => setTimeout(resolve, 200)); // 等待滚动完成

  // 🔧 [修复] 在点击前检查停止状态（包括全局停止标志）
  if (window.globalExecutionStopped) {
    console.log(`🛑 [全局停止] clickVirtualListItem检测到全局停止标志，停止执行`);
    const stopError = new Error("EXECUTION_STOPPED");
    stopError.isStopSignal = true;
    throw stopError;
  }

  if (window.simplifiedExecutionControl) {
    await window.simplifiedExecutionControl.checkPause();
  }

  // 根据循环类型决定如何处理
  if (step.loopType === "container") {
    // 容器循环：先点击容器按钮，再执行子操作
    console.log(`📦 容器循环模式：先点击容器按钮，再执行子操作`);

    // 1. 先点击容器按钮
    console.log(`👆 点击虚拟列表容器按钮`);
    highlightElement(targetButton, "click");
    targetButton.click();

    // 等待点击效果
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 清除点击高亮，改为容器高亮
    clearElementHighlight(targetButton);
    highlightElement(targetButton, "loop");

    // 2. 然后执行子操作序列
    if (step.subOperations && step.subOperations.length > 0) {
      console.log(
        `🔧 容器点击后，开始执行 ${step.subOperations.length} 个子操作`
      );

      for (let i = 0; i < step.subOperations.length; i++) {
        const subOp = step.subOperations[i];
        console.log(
          `🎯 执行容器内子操作 ${i + 1}: ${subOp.type} - ${subOp.locator?.value || subOp.locator
          }`
        );

        // 发送子操作步骤更新到浮层
        const subOpMessage = {
          type: 'FROM_CONTENT_SCRIPT',
          action: 'executionStatusUpdate',
          data: {
            isRunning: true,
            isPaused: false,
            message: `执行子操作 ${i + 1}/${step.subOperations.length}: ${subOp.type}`,
            currentStep: i + 1,
            totalSteps: step.subOperations.length
          },
          timestamp: Date.now()
        };
        window.postMessage(subOpMessage, '*');
        console.log('📤 发送子操作步骤更新到浮层:', subOpMessage.data);

        try {
          // 检查暂停状态
          if (window.simplifiedExecutionControl) {
            await window.simplifiedExecutionControl.checkPause();
          }

          // 传递容器元素上下文给子操作
          await executeSubOperation(subOp, targetButton);
        } catch (error) {
          // 如果是停止信号，直接重新抛出
          if (error.isStopSignal || error.message === 'EXECUTION_STOPPED') {
            console.log(`🛑 容器内子操作 ${i + 1} 收到停止信号，停止执行`);
            throw error;
          }

          console.error(`❌ 容器内子操作 ${i + 1} 失败:`, error);
          if (step.errorHandling === "stop") {
            throw error;
          }
        }

        // 子操作间等待
        if (subOp.delay || subOp.waitAfterClick) {
          const waitTime = subOp.delay || subOp.waitAfterClick || 500;
          console.log(`⏳ 子操作间等待 ${waitTime}ms`);
          await new Promise((resolve) => setTimeout(resolve, waitTime));
        }
      }

      console.log(`✅ 容器内所有子操作执行完成`);
    } else {
      console.log(`⚠️ 容器循环没有配置子操作`);
    }

    // 清除容器高亮
    setTimeout(() => {
      clearElementHighlight(targetButton);
    }, 1000);
  } else {
    // 非容器循环：只点击按钮
    console.log(`👆 点击虚拟列表按钮`);
    targetButton.click();
  }
}

// 敏感词检测测试函数
window.testSensitiveWordDetection = function () {
  console.log("=== 扩展程序敏感词检测测试 ===");

  if (!window.SensitiveWordDetector) {
    console.error("❌ SensitiveWordDetector 模块未加载");
    return false;
  }

  const detector = new window.SensitiveWordDetector();

  // 测试基本功能
  detector.setSensitiveWords("广告,推广,营销");
  console.log("设置的敏感词:", detector.sensitiveWords);

  const testText = "广告推广服务";
  const result = detector.detectSensitiveWords(testText);
  console.log(`文本 "${testText}" 检测结果:`, result);

  if (result.hasSensitiveWord && result.matchedWords.includes("广告")) {
    console.log("✅ 扩展程序中的敏感词检测正常工作");
    return true;
  } else {
    console.log("❌ 扩展程序中的敏感词检测有问题");
    return false;
  }
};

// ==================== 浮层控制面板支持 ====================

// 监听来自浮层控制面板的 postMessage
window.addEventListener('message', (event) => {
  // 确保消息来源是当前窗口
  if (event.source !== window) return;

  // 检查消息类型
  if (event.data.type === 'TO_BACKGROUND_SCRIPT') {
    const { payload } = event.data;
    console.log(`📡 Content script收到浮层消息，转发到background:`, payload);

    // 转发到 background script
    chrome.runtime.sendMessage({
      action: 'forwardToContentScript',
      targetAction: payload.action,
      targetData: payload.data
    }).then(response => {
      console.log(`✅ 消息转发成功:`, response);
      // 可以选择将响应发送回浮层面板
      if (response && response.success) {
        // 发送成功响应到浮层面板
        window.postMessage({
          type: 'FROM_CONTENT_SCRIPT',
          payload: {
            action: 'forwardResponse',
            success: true,
            data: response.response
          }
        }, '*');
      }
    }).catch(error => {
      console.error(`❌ 消息转发失败:`, error);
      // 发送错误响应到浮层面板
      window.postMessage({
        type: 'FROM_CONTENT_SCRIPT',
        payload: {
          action: 'forwardResponse',
          success: false,
          error: error.message
        }
      }, '*');
    });
  }
});



// 加载浮层控制面板模块
function loadFloatingControlPanel() {
  if (window.FloatingControlPanel) {
    console.log('🎛️ 浮层控制面板已存在，跳过加载');
    return;
  }

  try {
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('modules/content/floating-control-panel.js');
    script.onload = () => {
      console.log('✅ 浮层控制面板模块加载成功');
    };
    script.onerror = (error) => {
      console.error('❌ 浮层控制面板模块加载失败:', error);
    };
    document.documentElement.appendChild(script);
  } catch (error) {
    console.error('❌ 加载浮层控制面板失败:', error);
  }
}

// 页面加载完成后加载浮层控制面板
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', loadFloatingControlPanel);
} else {
  loadFloatingControlPanel();
}

console.log('✅ Content script 浮层支持已加载');

// 将executeSimplifiedWorkflow函数暴露到window对象，供其他模块调用
window.executeSimplifiedWorkflow = executeSimplifiedWorkflow;
console.log("✅ executeSimplifiedWorkflow函数已暴露到window对象");